Pick an option and check it. The explanation shows after each answer. Take as long as you like; nothing is timed and nothing is sent.
20 questions
Question 1 · easy
What does this Java 21 program print?
import java.util.Arrays;
public class Main {
static void reverse(int[] a, int lo, int hi) {
while (lo < hi) {
int t = a[lo]; a[lo] = a[hi]; a[hi] = t;
lo++; hi--;
}
}
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5, 6};
reverse(a, 1, 4);
System.out.println(Arrays.toString(a));
}
}
The two-pointer reversal swaps a[lo] and a[hi] and moves both pointers inward until they meet, so only the range from index 1 to index 4 (both inclusive) is reversed: 2, 3, 4, 5 becomes 5, 4, 3, 2. It runs in O(n) time with O(1) extra space, which is why interviewers expect it instead of copying into a new array. The same helper, called three times, also rotates an array in place.
Question 2 · easy
What does this Java 21 program print?
public class Main {
static boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i < j) {
if (s.charAt(i) != s.charAt(j)) return false;
i++; j--;
}
return true;
}
public static void main(String[] args) {
System.out.println(isPalindrome("racecar") + " " + isPalindrome("Madam")
+ " " + isPalindrome("abba"));
}
}
The check compares characters from both ends moving inward and stops when the pointers meet, which works for odd and even lengths alike, so abba is a palindrome. charAt comparison is case-sensitive: 'M' and 'm' are different characters, so Madam fails. If the interviewer wants case to be ignored, compare Character.toLowerCase of both characters.
Question 3 · medium
What does this Java 21 program print?
public class Main {
static boolean isAnagram(String a, String b) {
if (a.length() != b.length()) return false;
int[] count = new int[26];
for (int i = 0; i < a.length(); i++) {
count[a.charAt(i) - 'a']++;
count[b.charAt(i) - 'a']--;
}
for (int c : count) if (c != 0) return false;
return true;
}
public static void main(String[] args) {
System.out.println(isAnagram("listen", "silent") + " " + isAnagram("aab", "abb"));
}
}
An int[26] counter adds one for each letter of the first string and subtracts one for each letter of the second; the strings are anagrams only if every count returns to zero. aab and abb use the same set of letters but in different amounts, so the count for a ends at 1 and the method returns false. Comparing only the sets of letters is the classic mistake this catches; the method is O(n) time and O(1) space for lowercase letters.
Question 4 · medium
This method should reverse a string in place in a char[]. reverse("abc") returns cba, but reverse("abcd") returns dbca. Which change fixes it?
static String reverse(String s) {
char[] c = s.toCharArray();
int n = c.length;
for (int i = 0; i <= n / 2; i++) {
char t = c[i];
c[i] = c[n - 1 - i];
c[n - 1 - i] = t;
}
return new String(c);
}
Each swap fixes two positions, so only the first half of the indices may drive the loop: i < n / 2. With i <= n / 2 and an even length, the extra iteration swaps the two middle characters back, undoing the earlier swap; for odd lengths the extra iteration swaps the middle character with itself, which is why abc looked correct. Running the loop to n would swap every pair twice and return the original string.
Question 5 · easy
A candidate builds a comma-separated string of n numbers with result += nums[i] + ","; inside a loop. What should they say about this when the interviewer asks about performance?
Strings in Java are immutable, so every concatenation allocates a new String and copies the characters of the old one, and the copies grow with each iteration, giving quadratic total work. The compiler optimises concatenation within a single expression, not across loop iterations. A StringBuilder keeps one growable buffer, so each append is amortized O(1) and the loop is linear.
Question 6 · medium
What does this Java 21 program print?
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] nums = {3, 2, 4};
int target = 6;
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
Integer j = seen.get(target - nums[i]);
if (j != null) { System.out.println(j + " " + i); return; }
seen.put(nums[i], i);
}
System.out.println("none");
}
}
One-pass two-sum looks up the complement target - nums[i] before inserting the current value, so an element is never paired with itself: at index 0 the map is empty, so 3 is not matched with itself to make 6. At index 2 the complement 2 is found at index 1, and the earlier index is printed first. This gives O(n) time with an O(n) HashMap, instead of the O(n²) nested-loop solution.
Question 7 · easy
What does this Java 21 program print?
import java.util.*;
public class Main {
public static void main(String[] args) {
String s = "loveleetcode";
Map<Character, Integer> freq = new HashMap<>();
for (char c : s.toCharArray()) freq.merge(c, 1, Integer::sum);
int answer = -1;
for (int i = 0; i < s.length(); i++) {
if (freq.get(s.charAt(i)) == 1) { answer = i; break; }
}
System.out.println(answer);
}
}
The first pass counts every character; the second pass walks the string in its original order and returns the first index whose count is 1. In loveleetcode the letters l and o both appear again later, so the first character seen exactly once is v at index 2. Two linear passes give O(n) time, and the second pass must follow the string, not the map, because the map has no useful order.
Question 8 · medium
What does this Java 21 program print?
import java.util.*;
public class Main {
public static void main(String[] args) {
String[] words = {"eat", "tea", "tan", "ate", "nat", "bat"};
Map<String, List<String>> groups = new HashMap<>();
for (String w : words) {
char[] c = w.toCharArray();
Arrays.sort(c);
groups.computeIfAbsent(new String(c), k -> new ArrayList<>()).add(w);
}
System.out.println(groups.size() + " " + groups.get("aet"));
}
}
Sorting the letters of each word gives a canonical key, so all anagrams share one key: aet for eat, tea and ate, ant for tan and nat, and abt for bat, which makes 3 groups. computeIfAbsent creates the list the first time a key is seen and the words are appended in input order. The key must be a String built from the sorted array; using the char[] itself as a key would fail because arrays use identity equality.
Question 9 · easy
This method should count each character, but counts("aba") throws a NullPointerException. Which replacement for the line inside the loop makes it count a as 2 and b as 1?
static Map<Character, Integer> counts(String s) {
Map<Character, Integer> map = new HashMap<>();
for (char c : s.toCharArray()) {
map.put(c, map.get(c) + 1);
}
return map;
}
map.get(c) returns null for a character not yet in the map, and unboxing that null for + 1 throws the exception. merge inserts 1 when the key is absent and otherwise combines the old value with 1, which is exactly a counter; map.getOrDefault(c, 0) + 1 is the other common fix. putIfAbsent never increments, computeIfPresent never inserts, and starting a new key at 0 undercounts every character by one.
Question 10 · hard
Given an unsorted int[] of n values, return the length of the longest run of consecutive integers (for {100, 4, 200, 1, 3, 2} the answer is 4, from 1, 2, 3, 4). The interviewer asks for O(n) expected time. Which approach meets it?
Starting a count only at values with no predecessor means each run is walked exactly once, from its smallest element, so all the upward steps together total at most n and the algorithm is O(n) expected with O(1) HashSet lookups. Counting upward from every value repeats the same run many times and becomes O(n²) on input like 1, 2, ..., n. Sorting and a TreeSet both work but cost O(n log n).
Question 11 · easy
What does this Java 21 program print?
import java.util.*;
public class Main {
static boolean valid(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
int k = "([{".indexOf(c);
if (k >= 0) stack.push(")]}".charAt(k));
else if (stack.isEmpty() || stack.pop() != c) return false;
}
return stack.isEmpty();
}
public static void main(String[] args) {
System.out.println(valid("{[()]}") + " " + valid("([)]") + " " + valid("(("));
}
}
For each opening bracket the matching closing bracket is pushed; each closing bracket must equal the top of the stack, which enforces correct nesting, so ([)] fails even though the counts balance. The final isEmpty() check rejects unclosed brackets such as ((. ArrayDeque is the recommended stack in modern Java: the legacy Stack class is synchronized and extends Vector.
Question 12 · medium
A queue is built from two stacks (ArrayDeques used with push and pop). offer(x) pushes onto in. poll() pops from out, and only when out is empty does it first pop every element of in and push it onto out. What is the time complexity of poll()?
Every element is pushed onto in once, moved to out once and popped from out once, so n operations do O(n) total work, which is amortized O(1) per operation. A single poll() that finds out empty can still cost O(n) for the transfer. Moving elements back after each poll would destroy this guarantee and make the queue O(n) per operation.
Question 13 · hard
What does this Java 21 program print?
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] a = {2, 7, 3, 5, 4, 6, 8};
int[] next = new int[a.length];
Arrays.fill(next, -1);
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < a.length; i++) {
while (!stack.isEmpty() && a[stack.peek()] < a[i]) next[stack.pop()] = a[i];
stack.push(i);
}
System.out.println(Arrays.toString(next));
}
}
The stack holds indices of elements still waiting for a greater value to their right, in decreasing order of value. When a[i] is larger than the value at the top, it is the next greater element for that index, so the index is popped and answered; indices never answered keep -1. Each index is pushed and popped at most once, so this monotonic-stack solution is O(n) instead of the O(n²) scan to the right for every element.
Question 14 · medium
This BFS should list each node once in breadth-first order. On the graph with edges 0 -> 1, 0 -> 2, 1 -> 3 and 2 -> 3 it returns [0, 1, 2, 3, 3]. Which fix is right?
static List<Integer> bfs(List<List<Integer>> adj, int start) {
List<Integer> order = new ArrayList<>();
Deque<Integer> queue = new ArrayDeque<>();
boolean[] visited = new boolean[adj.size()];
queue.offer(start);
while (!queue.isEmpty()) {
int u = queue.poll();
visited[u] = true;
order.add(u);
for (int v : adj.get(u)) if (!visited[v]) queue.offer(v);
}
return order;
}
A node must be marked visited when it is added to the queue, not when it is removed; otherwise two neighbours can both enqueue the same node before it is ever polled, which is how 3 gets in twice. Checking order has the same flaw, since 3 is still waiting in the queue when node 2 is processed, and it adds an O(n) scan per edge. Switching to a stack or push changes the order to depth-first without fixing the duplicates.
Question 15 · medium
Design a stack of ints that supports push, pop, top and getMin, each in O(1) time. Which design works?
The minimum depends on which elements are still on the stack, so it must be remembered per level: the auxiliary stack's top is always the minimum of the elements currently in the main stack, and popping both keeps them in sync. A single min field cannot recover the previous minimum after the minimum is popped. A PriorityQueue makes push O(log n) and removing an arbitrary popped value O(n), and sorting on every push is O(n log n).
Question 16 · easy
What is the time complexity of this fragment in terms of n?
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
count++;
}
}
The inner loop runs n - 1, n - 2, ..., 1, 0 times, which sums to n(n - 1)/2. Big-O keeps only the fastest-growing term and drops constant factors such as 1/2, so this is O(n²), the same class as the full n by n loop. This is the pattern of checking every pair once, as in brute-force two-sum.
Question 17 · medium
An interviewer asks: what is the time complexity of HashMap.get(key) in Java 21?
get hashes the key to a bucket index in O(1) and then compares only the few entries in that bucket, so the average cost is constant when keys spread evenly. If many keys share a bucket, for example because hashCode returns a constant, lookups degrade; since Java 8 a bucket that grows large is converted from a linked list to a balanced tree to limit the damage. A sorted map with guaranteed O(log n) operations is TreeMap, not HashMap.
Question 18 · medium
jobs is an ArrayList with n = 100,000 items, and this method is far slower than expected. What is the cause and the right fix?
static long sumAll(List<Integer> jobs) {
long total = 0;
while (!jobs.isEmpty()) {
total += jobs.remove(0);
}
return total;
}
An ArrayList stores its elements in a contiguous array, so removing index 0 copies all the elements after it, which is O(n) per call and about n²/2 copies in total. ArrayDeque.pollFirst() removes from the front in O(1), and a plain for-each loop over the list does the sum in O(n) without removing anything. isEmpty() and size() are O(1), and an ArrayList does not shrink its array on removal.
Question 19 · easy
What does this Java 21 program print?
public class Main {
public static void main(String[] args) {
int n = 100, outer = 0, inner = 0;
for (int i = 1; i < n; i *= 2) {
outer++;
for (int j = 0; j < n; j++) inner++;
}
System.out.println(outer + " " + inner);
}
}
The outer variable doubles each time (1, 2, 4, 8, 16, 32, 64), so the outer loop runs about log2(n) times, here 7, while the inner loop runs n = 100 times on every pass, giving 700. In general a doubling loop is O(log n), and nesting an O(n) loop inside it makes O(n log n). Recognising the multiplying step instead of i++ is what interviewers check here.
Question 20 · hard
You must report whether an int[] of n values contains a duplicate, in O(n log n) time, without allocating any extra collection or array (modifying the input is allowed). Which approach meets both limits?
After sorting, equal values sit next to each other, so a single O(n) scan of neighbours finds a duplicate, and Arrays.sort on a primitive array is O(n log n) and sorts in place. A HashSet gives O(n) expected time but needs O(n) extra memory, which breaks the space limit, and a TreeSet also needs O(n) memory. Nested loops use no extra memory but take O(n²) time; naming this time-versus-space trade-off is the point of the question.
Your answers stay in this browser tab. Nothing is sent or saved.