Category: java
java interview questions
Published on 16 May 2026
Explanation
Find the majority element in an
array using Boyer-Moore Voting Algorithm.
Code:
int[] arr = {2,2,1,1,2,2,2};
int candidate = 0, count = 0;
for(int num : arr) {
if(count == 0) {
candidate = num;
}
count += (num == candidate) ? 1 : -1;
}
System.out.println(candidate);
Explanation
Check if two strings are anagrams
using character counting.
Code:
String s1 = "listen";
String s2 = "silent";
int[] freq = new int[26];
for(char ch : s1.toCharArray())
freq[ch - 'a']++;
for(char ch : s2.toCharArray())
freq[ch - 'a']--;
boolean isAnagram = true;
for(int val : freq) {
if(val != 0) {
isAnagram = false;
break;
}
}
System.out.println(isAnagram);
Explanation
Find the first non-repeating character in
a string.
Code:
String str = "aabbcdde";
Map<Character, Integer> map =
new LinkedHashMap<>();
for(char ch : str.toCharArray()) {
map.put(ch,
map.getOrDefault(ch, 0) + 1);
}
for(Map.Entry<Character, Integer> entry :
map.entrySet()) {
if(entry.getValue() == 1) {
System.out.println(entry.getKey());
break;
}
}
Explanation
Find the longest substring without repeating
characters using sliding window.
Code:
String str = "abcabcbb";
Set<Character> set = new HashSet<>();
int left = 0, max = 0;
for(int right = 0; right < str.length();
right++) {
while(set.contains(str.charAt(right))) {
set.remove(str.charAt(left++));
}
set.add(str.charAt(right));
max = Math.max(max, right - left + 1);
}
System.out.println(max);
Explanation
Rotate an array by k positions.
Code:
int[] arr = {1,2,3,4,5,6,7};int k = 3;
k = k % arr.length;
reverse(arr, 0, arr.length - 1);
reverse(arr, 0, k - 1);
reverse(arr, k, arr.length - 1);
public static void reverse(int[] arr,
int start, int end) {
while(start < end) {
int temp = arr[start];
arr[start++] = arr[end];
arr[end--] = temp;
}
}