Autocoder

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.

LanguageJava 17 and later
Problems15, mostly easy and medium
FocusCorrectness first, then complexity

Habits that win marks in a Java coding test

Java Coding Interview Questions: questions with worked answers

  1. 1

    Two Sum: return the indices of two numbers that add to a target.

    easy

    Store 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.

    java
    static 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. 2

    Valid parentheses: check whether brackets are balanced.

    easy

    Push 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.

    java
    static 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("(]") -> false
  3. 3

    Find the first non-repeating character in a string.

    easy

    Count 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.

    java
    static 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") -> -1
  4. 4

    Print the Fibonacci number n iteratively. When does long overflow?

    easy

    Keep 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.

    java
    static 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) -> 7540113804746346429
  5. 5

    Check whether a number is prime.

    easy

    Trial 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.

    java
    static 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. 6

    Compute the GCD and LCM of two numbers.

    easy

    Euclid: 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.

    java
    static 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) -> 12
  7. 7

    Maximum subarray sum (Kadane).

    medium

    At 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.

    java
    static 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}) -> 6
  8. 8

    Binary search, and the midpoint overflow bug.

    medium

    Keep 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.

    java
    static 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. 9

    Rotate an array right by k in place.

    medium

    Reverse 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.

    java
    static 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. 10

    Reverse a singly linked list.

    medium

    Walk 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.

    java
    static 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. 11

    Detect a cycle in a linked list.

    medium

    Floyd'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.

    java
    static 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. 12

    Merge two sorted arrays into one.

    medium

    Use 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.

    java
    static 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. 13

    Remove duplicates from a sorted array in place.

    medium

    Use 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.

    java
    static 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. 14

    Swap two numbers without a temporary variable. What are the traps?

    easy

    With 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.

    java
    int a = 5, b = 9;
    a = a ^ b; b = a ^ b; a = a ^ b;
    System.out.println(a + " " + b);  // 9 5
  15. 15

    Design a thread-safe counter and explain what the JIT does to it.

    hard

    Use 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.

    java
    class 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

See all in this section