Java Coding Interview Questions
Last updated 2026-11-19
Coding rounds in Java check two things at once: can you solve the problem, and do you write idiomatic Java while doing it. That means choosing the right collection, using StringBuilder instead of repeated concatenation, and avoiding traps such as integer overflow in a binary search midpoint.
Each solution below compiles on Java 17 and states its time and space complexity. For the process around these rounds, see how to crack a DSA coding round and the topic pages in the DSA hub.
| Language | Java 17 and later |
|---|---|
| Problems | 15, mostly easy and medium |
| Focus | Correctness first, then complexity |
Habits that win marks in a Java coding test
- State the brute force and its complexity before you optimise.
- Use int for counts, long when a sum or product can pass 2 billion.
- Use ArrayDeque for stacks and queues, HashMap for lookup, StringBuilder for building text.
- Check empty input, a single element and duplicates before submitting.
Java Coding Interview Questions: questions with worked answers
1 Two Sum: return the indices of two numbers that add to a target.
easyStore each value with its index in a HashMap and, for each number, look up target minus the number. One pass gives O(n) time and O(n) space. The brute force of two loops is O(n squared). Check for the complement before inserting so an element is not paired with itself.
javastatic int[] twoSum(int[] a, int target) { Map<Integer,Integer> seen = new HashMap<>(); for (int i = 0; i < a.length; i++) { Integer j = seen.get(target - a[i]); if (j != null) return new int[]{j, i}; seen.put(a[i], i); } return new int[0]; } // twoSum(new int[]{2,7,11,15}, 9) -> [0, 1]2 Valid parentheses: check whether brackets are balanced.
easyPush opening brackets on a stack and, on a closing bracket, pop and compare with the matching opener. The string is valid if the stack is empty at the end. O(n) time, O(n) space.
javastatic boolean valid(String s) { Deque<Character> st = new ArrayDeque<>(); for (char ch : s.toCharArray()) { if (ch == '(') st.push(')'); else if (ch == '[') st.push(']'); else if (ch == '{') st.push('}'); else if (st.isEmpty() || st.pop() != ch) return false; } return st.isEmpty(); } // valid("{[()]}") -> true, valid("(]") -> false3 Find the first non-repeating character in a string.
easyCount occurrences first, then scan the string again and return the first character whose count is 1. For lowercase ASCII an int[26] makes it O(n) time and O(1) space; use a LinkedHashMap or a count array of size 128 or more for general text.
javastatic int firstUnique(String s) { int[] cnt = new int[26]; for (char ch : s.toCharArray()) cnt[ch - 'a']++; for (int i = 0; i < s.length(); i++) if (cnt[s.charAt(i) - 'a'] == 1) return i; return -1; } // firstUnique("leetcode") -> 0, firstUnique("aabb") -> -14 Print the Fibonacci number n iteratively. When does long overflow?
easyKeep two variables and advance them n times for O(n) time and O(1) space. The naive recursion fib(n-1) + fib(n-2) is O(2^n). fib(92) is the last Fibonacci number that fits in a signed long (7540113804746346429); fib(93) overflows, so use BigInteger beyond that or Math.addExact to fail loudly.
javastatic long fib(int n) { long a = 0, b = 1; for (int i = 0; i < n; i++) { long t = a + b; a = b; b = t; } return a; } // fib(10) -> 55, fib(92) -> 75401138047463464295 Check whether a number is prime.
easyTrial division up to the square root is enough: if n has a factor larger than its root, it has a smaller one too. Handle n below 2 and even numbers first. Time O(sqrt n), space O(1). Write the loop condition as i <= n / i to avoid overflow of i * i.
javastatic boolean isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; for (int i = 3; i <= n / i; i += 2) if (n % i == 0) return false; return true; }6 Compute the GCD and LCM of two numbers.
easyEuclid: gcd(a, b) = gcd(b, a % b) until b is 0. It takes O(log min(a, b)) steps. lcm is a / gcd * b, dividing first to reduce the risk of overflow.
javastatic int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static long lcm(int a, int b) { return (long) a / gcd(a, b) * b; } // gcd(12, 18) -> 6, lcm(4, 6) -> 127 Maximum subarray sum (Kadane).
mediumAt each element decide whether to extend the running subarray or start fresh: cur = max(a[i], cur + a[i]). Track the best value seen. O(n) time, O(1) space, and it works with all negative numbers because it starts from a[0] rather than 0.
javastatic int maxSub(int[] a) { int best = a[0], cur = a[0]; for (int i = 1; i < a.length; i++) { cur = Math.max(a[i], cur + a[i]); best = Math.max(best, cur); } return best; } // maxSub(new int[]{-2,1,-3,4,-1,2,1,-5,4}) -> 68 Binary search, and the midpoint overflow bug.
mediumKeep lo and hi and halve the range each step: O(log n) time, O(1) space, array must be sorted. Computing (lo + hi) / 2 can overflow when both are large; use lo + (hi - lo) / 2 or (lo + hi) >>> 1. This exact bug existed in the JDK for years.
javastatic int search(int[] a, int key) { int lo = 0, hi = a.length - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (a[mid] == key) return mid; if (a[mid] < key) lo = mid + 1; else hi = mid - 1; } return -1; }9 Rotate an array right by k in place.
mediumReverse the whole array, then reverse the first k elements, then the rest. Reduce k with k % n first. O(n) time and O(1) space, beating the copy approach in space.
javastatic void rotate(int[] a, int k) { int n = a.length; k %= n; rev(a, 0, n - 1); rev(a, 0, k - 1); rev(a, k, n - 1); } static void rev(int[] a, int i, int j) { while (i < j) { int t = a[i]; a[i++] = a[j]; a[j--] = t; } } // [1,2,3,4,5,6,7], k=3 -> [5,6,7,1,2,3,4]10 Reverse a singly linked list.
mediumWalk once, flipping each next pointer, while holding the previous node. O(n) time and O(1) space. The recursive version uses O(n) stack and can overflow on long lists.
javastatic class Node { int val; Node next; Node(int v) { val = v; } } static Node reverse(Node head) { Node prev = null; while (head != null) { Node nxt = head.next; head.next = prev; prev = head; head = nxt; } return prev; }11 Detect a cycle in a linked list.
mediumFloyd's tortoise and hare: one pointer moves one step, the other two. If they meet there is a cycle; if the fast one reaches null there is none. O(n) time, O(1) space, versus O(n) space for a HashSet of visited nodes.
javastatic boolean hasCycle(Node head) { Node slow = head, fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; if (slow == fast) return true; } return false; }12 Merge two sorted arrays into one.
mediumUse two indices and always take the smaller head element, then copy the leftovers. O(m + n) time and O(m + n) output space. Using <= when comparing keeps the merge stable.
javastatic int[] merge(int[] a, int[] b) { int[] r = new int[a.length + b.length]; int i = 0, j = 0, k = 0; while (i < a.length && j < b.length) r[k++] = a[i] <= b[j] ? a[i++] : b[j++]; while (i < a.length) r[k++] = a[i++]; while (j < b.length) r[k++] = b[j++]; return r; }13 Remove duplicates from a sorted array in place.
mediumUse a write pointer for the next unique slot and a read pointer that scans. Whenever a[read] differs from the last kept value, copy it. O(n) time, O(1) space, and the return value is the new length.
javastatic int dedupe(int[] a) { if (a.length == 0) return 0; int w = 1; for (int r = 1; r < a.length; r++) if (a[r] != a[w - 1]) a[w++] = a[r]; return w; } // [1,1,2,2,3] -> length 3, prefix [1,2,3]14 Swap two numbers without a temporary variable. What are the traps?
easyWith arithmetic: a = a + b; b = a - b; a = a - b. With XOR: a ^= b; b ^= a; a ^= b. The arithmetic version can overflow silently, though the final values are still correct under wraparound arithmetic. The XOR version breaks if both names refer to the same array element, since it zeroes it. A temporary variable is clearer and is what the JIT optimises anyway.
javaint a = 5, b = 9; a = a ^ b; b = a ^ b; a = a ^ b; System.out.println(a + " " + b); // 9 515 Design a thread-safe counter and explain what the JIT does to it.
hardUse AtomicLong for a single counter: incrementAndGet is a lock-free compare-and-swap. For heavily contended counters LongAdder spreads updates over cells and sums on read, giving better throughput but a non-atomic snapshot. A synchronized method is also correct and simpler. The point of the question is to avoid a plain long field with a ++ operation.
javaclass Counter { private final java.util.concurrent.atomic.AtomicLong n = new java.util.concurrent.atomic.AtomicLong(); long inc() { return n.incrementAndGet(); } long get() { return n.get(); } }
Frequently asked questions
Which Java collections should I know for coding rounds?
ArrayList, HashMap, HashSet, ArrayDeque, PriorityQueue and TreeMap cover nearly every problem.
Should I use recursion in Java?
Only where depth is bounded. Java has no tail-call optimisation, so recursion on 100,000 elements can raise StackOverflowError.
How do I read input fast in Java?
Use BufferedReader with StringTokenizer or a custom reader, since Scanner is slow for large inputs.
Where can I practise topic by topic?
The DSA interview questions hub lists arrays, strings, trees, heaps and more with worked answers.
Related guides
More in Programming Language Interview Questions by Language
- Java Collections Interview Questions
- Java Concurrency Utilities Interview Questions
- Java Exception Handling Interview Questions
- Java Garbage Collection Interview Questions
- Java Generics Interview Questions
- Java HashMap Internals Interview Questions
- Java Interfaces and Abstract Classes Interview Questions
- Java Interview Questions and Answers
- Java Multithreading Interview Questions
- Java OOPs Interview Questions
- Java String Interview Questions
- JavaScript Array Methods Interview Questions