Common Java coding problems with working code, what each one tests, and the Java-specific mistakes that can sink a correct algorithm.
Java coding interview questions come in two kinds. The first is an ordinary algorithm problem (reverse a list, find a pair that sums to a target, build an LRU cache) that you happen to solve in Java. The second is a question where knowing Java changes the answer: why two Integer values fail an == check, why a HashSet cannot find an object you just added, why removing items in a for-each loop throws. Practising only the first kind leaves you exposed to the second, because a solution can be logically right and still be wrong in Java. Below: how a live Java round is set up, 15 questions (most with working code, the last three for experienced candidates), a worked LRU cache example in two versions, and a one-week plan.
If you want to see where the Java coding round fits among the other stages, our guide to the software engineer interview process, round by round lays out the whole sequence.
Before the round: check the setup
Some live coding rounds run in a shared online editor such as CoderPad rather than in your own IDE. Two things about the setup change how you write code, so check them early.
The Java version. CoderPad's Java page says it runs OpenJDK 20. That covers records (final in Java 16) and switch expressions with ->, but not features finalized later, such as virtual threads, which became final in Java 21. If you plan to use anything recent, ask or run a one-line test first.
The entry point and libraries. CoderPad expects a public class named Solution with a public static void main, and puts JUnit and Guava on the classpath. Write a few calls in main that print results for normal input and an edge case. It takes a minute and shows the interviewer you test your own code.
Then choose your tools. These classes cover every problem below:
- You need — Use — Why this one
- A stack or a queue —
ArrayDeque— The Javadoc says it is likely faster thanStackused as a stack and faster thanLinkedListused as a queue. It rejectsnull. - Lookup by key —
HashMap— Constant-timegetandputif hashing spreads keys well. No ordering guarantee. - Lookup in insertion or access order —
LinkedHashMap— Iterates in insertion order, or in access order with the three-argument constructor. - The smallest (or largest) item, repeatedly —
PriorityQueue—offerandpollare O(log n),peekis constant time. Iterating it is not sorted. - Building a string in a loop —
StringBuilder—Stringis immutable, so repeated+in a loop creates new strings. - Shared counters or maps across threads —
AtomicInteger,ConcurrentHashMap—HashMap,ArrayListandStringBuilderare not thread-safe.
Strings and arrays
1. Reverse a string without `StringBuilder.reverse()`.
Tests: loops, indexes, and whether you know String cannot be changed in place.
static String reverse(String s) {
char[] a = s.toCharArray();
for (int i = 0, j = a.length - 1; i < j; i++, j--) {
char t = a[i]; a[i] = a[j]; a[j] = t;
}
return new String(a);
}O(n) time, O(n) extra space for the array. The follow-up that separates candidates: what happens with an emoji? length() counts UTF-16 code units, and many emoji take two of them (a surrogate pair). Swapping char values splits the pair and corrupts the character. StringBuilder.reverse() treats surrogate pairs as single characters, so mention that it handles the case your loop does not.
2. Check whether two strings are anagrams.
Tests: choosing a counting structure. For lowercase English letters, an int[26] is the simplest answer:
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;
}State the assumption out loud ("lowercase a to z only"). If the input can be any text, switch to a HashMap keyed by code point (s.codePoints()), so characters made of two char values are counted once. Sorting both char[] arrays and comparing them also works, at O(n log n).
3. Two sum: return the indexes of two numbers that add up to a target.
Tests: trading memory for time. The brute-force double loop is O(n²). One pass with a map from value to index is O(n):
static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
Integer j = seen.get(target - nums[i]);
if (j != null) return new int[] { j, i };
seen.put(nums[i], i);
}
return new int[0];
}Note the Integer j and the null check: get returns null for a missing key, and unboxing that into an int throws a NullPointerException.
4. Find the first character that does not repeat.
Tests: whether you know an ordered map exists. A LinkedHashMap keeps insertion order, so one pass counts and a second pass over the map finds the answer:
static Character firstUnique(String s) {
Map<Character, Integer> counts = new LinkedHashMap<>();
for (char c : s.toCharArray()) counts.merge(c, 1, Integer::sum);
for (Map.Entry<Character, Integer> e : counts.entrySet()) {
if (e.getValue() == 1) return e.getKey();
}
return null;
}merge(c, 1, Integer::sum) inserts 1 for a new key and adds 1 otherwise, which replaces the usual containsKey branch.
5. Find the second largest number in an array.
Tests: edge cases more than the loop. What if the array has one element, or every element is equal? A common answer starts both trackers at Integer.MIN_VALUE, which breaks when the array itself contains that value. Track whether each value has been set instead:
static OptionalInt secondLargest(int[] nums) {
boolean hasFirst = false, hasSecond = false;
int first = 0, second = 0;
for (int n : nums) {
if (!hasFirst || n > first) {
if (hasFirst) { second = first; hasSecond = true; }
first = n; hasFirst = true;
} else if (n != first && (!hasSecond || n > second)) {
second = n; hasSecond = true;
}
}
return hasSecond ? OptionalInt.of(second) : OptionalInt.empty();
}This returns the second largest distinct value, so [5, 5] has none. Ask whether the interviewer wants that or wants 5; the question is ambiguous on purpose.
Data structures
6. Reverse a singly linked list.
Tests: pointer handling without losing the rest of the list.
static Node reverse(Node head) {
Node prev = null, cur = head;
while (cur != null) {
Node next = cur.next; // save before overwriting
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}O(n) time, O(1) space. Walk through a three-node list on screen before you say it works.
7. Check that brackets are balanced.
Tests: recognising a stack problem, and picking the right stack class.
static boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
switch (c) {
case '(' -> stack.push(')');
case '[' -> stack.push(']');
case '{' -> stack.push('}');
default -> { if (stack.isEmpty() || stack.pop() != c) return false; }
}
}
return stack.isEmpty();
}Pushing the expected closing bracket keeps the comparison to one line. If you reach for java.util.Stack, expect a question about why ArrayDeque is preferred.
8. Find the kth largest element.
Tests: heaps. Keep a min-heap of size k; its head is the answer.
static int kthLargest(int[] nums, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<>();
for (int n : nums) {
heap.offer(n);
if (heap.size() > k) heap.poll();
}
return heap.peek();
}O(n log k). The Java trap is in the comparator when you need a max-heap: (a, b) -> b - a overflows when the values are far apart (for example, 1 and Integer.MIN_VALUE) and returns the wrong sign. Use Comparator.reverseOrder() or Integer.compare(b, a).
Questions where Java changes the answer
9. Why does `a == b` work for some `Integer` values and not others?
== on objects compares references. Integer.valueOf always caches -128 to 127, and the language spec guarantees identical boxed objects for constant expressions in that range. Outside it, two boxed values may be different objects, so == is usually false even when the numbers match. The real-world version of this bug: counts.get(a) == counts.get(b) on a Map<String, Integer> passes every small test and fails once a count passes 127. Use .equals(), or unbox to int first.
10. You added an object to a `HashSet` and `contains` says it is not there. Why?
Two likely causes. First, the class overrides equals but not hashCode. The Object contract says equal objects must have equal hash codes, so a lookup that hashes to a different bucket will usually not find the equal object, even though equals would say it matches. Second, a field used in equals changed after the object went into the set; the Map docs warn that behaviour is unspecified when a key changes that way. For small value classes, a record avoids the first problem: it generates equals and hashCode from its components.
11. Why does this loop throw `ConcurrentModificationException`?
for (String name : names) {
if (name.isEmpty()) names.remove(name); // usually throws ConcurrentModificationException
}ArrayList iterators are fail-fast: changing the list's structure during iteration, other than through the iterator's own remove or add, usually makes the next step throw. The exception has nothing to do with threads. Fix it with names.removeIf(String::isEmpty) or an explicit Iterator and it.remove(). The Javadoc adds that the check is best effort, so never rely on the exception for correctness.
12. What is wrong with `int mid = (low + high) / 2;`?
For very large arrays, low + high can exceed Integer.MAX_VALUE and wrap to a negative number. Joshua Bloch described this bug in 2006; it was in the binary search he wrote for java.util.Arrays. Write low + (high - low) / 2 or (low + high) >>> 1. Using the safe form without being asked is an easy signal that you know Java's int limits.
For experienced candidates: concurrency
Questions for mid-level and senior roles can move from algorithms to shared state. Here are three common concurrency topics.
13. Make this counter thread-safe. count++ is not one step: Oracle's concurrency tutorial breaks it into read, increment and write, and shows two threads losing an update. Answers in order of preference for a simple counter: AtomicInteger.incrementAndGet(), or a synchronized method. Explain why volatile alone does not fix it: the same tutorial says changes to a volatile variable are always visible to other threads, but an increment is still a read and a write that another thread can get between.
14. Count words from several threads. map.put(w, map.get(w) + 1) on a HashMap is unsafe twice: the map is not thread-safe, and get-then-put is a race even on a thread-safe map. On a ConcurrentHashMap, merge(w, 1L, Long::sum) is atomic. For heavily contended counters, the class docs suggest computeIfAbsent(w, k -> new LongAdder()).increment(). Mention that ConcurrentHashMap rejects null keys and values, unlike HashMap.
15. Write a producer-consumer. Use a BlockingQueue: put waits when the queue is full, take waits when it is empty, and the docs say it is safe with multiple producers and consumers. A bounded ArrayBlockingQueue stops a fast producer from filling memory. Handle InterruptedException instead of swallowing it, and be ready to explain how the consumers know to stop (a sentinel item, or interrupting them).
Worked example: design an LRU cache
This is a common Java coding problem because it has a short library answer and a longer hand-built one, and interviewers learn something from which one you choose. Ask first: "May I use LinkedHashMap?"
Version 1, with the library. LinkedHashMap has an access-order mode, and its Javadoc says it is well suited to LRU caches. removeEldestEntry runs after put inserts a new entry:
class LRUCache<K, V> extends LinkedHashMap<K, V> {
private final int capacity;
LRUCache(int capacity) {
super(16, 0.75f, true); // true = order by access, not insertion
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
}
}What makes this answer strong is what you say next. In access-order mode, get counts as an access, and the docs call a plain get a structural modification. So calling get while iterating the cache can throw ConcurrentModificationException, and the class is not synchronized; wrap it with Collections.synchronizedMap or guard it with a lock if threads share it.
Version 2, by hand. If the interviewer says no library, combine a HashMap for O(1) lookup with a doubly linked list for O(1) reordering:
class LRUCache {
private final int capacity;
private final Map<Integer, Node> map = new HashMap<>();
private final Node head = new Node(0, 0), tail = new Node(0, 0); // sentinels
LRUCache(int capacity) {
if (capacity < 1) throw new IllegalArgumentException("capacity must be at least 1");
this.capacity = capacity;
head.next = tail;
tail.prev = head;
}
int get(int key) {
Node n = map.get(key);
if (n == null) return -1;
unlink(n);
addFirst(n);
return n.value;
}
void put(int key, int value) {
Node n = map.get(key);
if (n != null) {
n.value = value;
unlink(n);
addFirst(n);
return;
}
if (map.size() == capacity) {
Node lru = tail.prev;
unlink(lru);
map.remove(lru.key);
}
n = new Node(key, value);
map.put(key, n);
addFirst(n);
}
private void unlink(Node n) { n.prev.next = n.next; n.next.prev = n.prev; }
private void addFirst(Node n) {
n.next = head.next; n.prev = head;
head.next.prev = n; head.next = n;
}
private static final class Node {
final int key; int value; Node prev, next;
Node(int key, int value) { this.key = key; this.value = value; }
}
}The details worth pointing out as you write it:
- The sentinel nodes remove every "is this the first or last node?" branch from
unlinkandaddFirst. - Each node stores its key. When you evict the tail node you need the key to remove it from the map. Leaving it out is an easy bug to make under time pressure.
- Updating an existing key moves it to the front. A
puton a key that exists is a use, not just a write. - The capacity check rejects a cache of size 0, which would otherwise try to evict a sentinel.
Weak answers stop at "it works for the example". Strong ones name the complexity (O(1) for both operations), test a capacity of 1, and say what would change for concurrent use.
A one-week plan
- Day 1: Set up a plain Java file with a
Solutionclass and amainmethod, as the editor will expect. Write questions 1 to 5 without an IDE's autocomplete. - Day 2: Questions 6 to 8. For each, say the time and space complexity out loud before running it.
- Day 3: Questions 9 to 12. Write a tiny program that shows each trap happening, so you can describe it from experience rather than memory.
- Day 4: The LRU cache, both versions, from a blank file. Time the hand-built version.
- Day 5: Concurrency: a broken counter, then the fixed one, then a producer-consumer with a bounded queue.
- Day 6: Two timed problems you have not seen, talking through your approach before you type.
- Day 7: Review your mistakes from the week. Prepare one short story about a bug you fixed in real Java code, in case the interviewer asks where you have used this.
For theory-style questions, see our Java viva questions. For later rounds in a Java backend loop, see the guides to Spring Security interview questions and Java architect interview questions.
Verve AI's Coding Copilot captures a question from your screen and returns a solution in 21+ programming languages, including Java, with quick actions such as Complexity, Edge Case and Optimize. It works best when the whole question, including constraints and examples, is in the capture.
Sources
- CoderPad runs OpenJDK 20, public class Solution with main, JUnit and Guava available: https://coderpad.io/languages/java/
- Records final in JDK 16; generated equals, hashCode, accessors: https://openjdk.org/jeps/395
- Virtual threads final in JDK 21: https://openjdk.org/jeps/444
- ArrayDeque faster than Stack and LinkedList, nulls prohibited, not thread-safe: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/ArrayDeque.html
- HashMap constant-time get/put, no order guarantee, nulls allowed, not synchronized: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/HashMap.html
- LinkedHashMap insertion and access order, LRU suitability, removeEldestEntry, get as structural modification, not synchronized: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/LinkedHashMap.html
- PriorityQueue complexity, unordered iteration: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/PriorityQueue.html
- String immutability, length() counts UTF-16 code units: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/String.html
- StringBuilder.reverse() treats surrogate pairs as single characters, not thread-safe: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/StringBuilder.html
- Boxing guarantees identity for -128 to 127: https://docs.oracle.com/javase/specs/jls/se21/html/jls-5.html
- Integer.valueOf caches -128 to 127, Integer.compare, MAX_VALUE: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Integer.html
- equals and hashCode contract: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Object.html
- Mutable map keys warning, merge(): https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html
- ArrayList fail-fast iterators, best-effort ConcurrentModificationException, not synchronized: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/ArrayList.html
- removeIf uses Iterator.remove: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Collection.html
- Binary search overflow, the java.util.Arrays bug, both fixes: https://research.google/blog/extra-extra-read-all-about-it-nearly-all-binary-searches-and-mergesorts-are-broken/
- c++ decomposes into three steps, lost update example: https://docs.oracle.com/javase/tutorial/essential/concurrency/interfere.html
- volatile changes always visible to other threads; increments are not atomic: https://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html
- ConcurrentHashMap rejects nulls, atomic merge and computeIfAbsent, LongAdder frequency map: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/concurrent/ConcurrentHashMap.html
- BlockingQueue put/take, thread-safe with multiple producers and consumers: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/concurrent/BlockingQueue.html
- Coding Copilot capture, 21+ languages including Java, quick actions, full-question tip: https://docs.vervecopilot.com/features/coding-copilot
Ryan, CEO of Verve AI
Interview Questions






