Skip to content
Laviyx Learn

Try

Java course menu

Java Coding Challenges for Interviews (With Solutions)

Classic Java coding interview problems with hints and full solutions: two sum, valid parentheses, anagram check, reverse words, maximum subarray (Kadane), merge sorted arrays, binary search, longest substring without repeating characters, group anagrams, and an LRU cache with LinkedHashMap.

Intermediate16 min readUpdated
On this page

These are classic problems from coding interviews and online assessments. Each teaches a reusable technique: hashing, stacks, two pointers, sliding windows or running totals. Try each one for at least 10 minutes before opening the hint, and state the time and space complexity of your answer.

Challenge 1: Two Sum#

Two Sum

Return the indexes of two numbers in an array that add up to a target, or [-1, -1]. Example: {2, 7, 11, 15}, target 9 → [0, 1].

Show hint

For each number, the partner you need is target - n. A HashMap from value to index answers "have I seen it?" in O(1).

Show solution
Java
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class TwoSum {
    static int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> seen = new HashMap<>();   // value -> index
        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[] {-1, -1};
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(twoSum(new int[] {2, 7, 11, 15}, 9)));
        System.out.println(Arrays.toString(twoSum(new int[] {3, 2, 4}, 6)));
        System.out.println(Arrays.toString(twoSum(new int[] {1, 2}, 10)));
    }
}
Output
[0, 1]
[1, 2]
[-1, -1]

O(n) time, O(n) space.

Challenge 2: Valid Parentheses#

Valid Parentheses

Return whether every bracket in a string of ()[]{} is closed in the correct order.

Show hint

Push opening brackets onto an ArrayDeque; each closing bracket must match the top.

Show solution
Java
import java.util.ArrayDeque;
import java.util.Deque;

public class Brackets {
    static boolean isValid(String s) {
        Deque<Character> stack = new ArrayDeque<>();
        for (char c : s.toCharArray()) {
            switch (c) {
                case '(', '[', '{' -> stack.push(c);
                default -> {
                    char open = c == ')' ? '(' : c == ']' ? '[' : '{';
                    if (stack.isEmpty() || stack.pop() != open) return false;
                }
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        for (String s : new String[] {"{[()]}", "([)]", "((", ""}) {
            System.out.print(isValid(s) + " ");
        }
        System.out.println();
    }
}
Output
true false false true 

O(n) time, O(n) space.

Challenge 3: Valid Anagram#

Valid Anagram

Return whether two lowercase strings are anagrams. "listen" / "silent" → true.

Show hint

Count letters in an int[26]: add for one string, subtract for the other.

Show solution
Java
public class Anagram {
    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("rat", "car"));
    }
}
Output
true false

O(n) time, O(1) space.

Challenge 4: Group Anagrams#

Group Anagrams

Group the words {"eat", "tea", "tan", "ate", "nat", "bat"} so that anagrams are together.

Show hint

Two words are anagrams if their sorted letters are equal. Use the sorted word as a map key.

Show solution
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class GroupAnagrams {
    public static void main(String[] args) {
        String[] words = {"eat", "tea", "tan", "ate", "nat", "bat"};
        Map<String, List<String>> groups = new TreeMap<>();

        for (String w : words) {
            char[] letters = w.toCharArray();
            Arrays.sort(letters);
            groups.computeIfAbsent(new String(letters), k -> new ArrayList<>()).add(w);
        }
        System.out.println(groups.values());
    }
}
Output
[[bat], [eat, tea, ate], [tan, nat]]

O(n · k log k) for n words of length k. A TreeMap keeps the output order predictable; a HashMap would be slightly faster.

Challenge 5: Maximum Subarray Sum#

Maximum Subarray (Kadane)

Find the largest sum of a contiguous subarray. For {-2, 1, -3, 4, -1, 2, 1, -5, 4} it is 6.

Show hint

The best subarray ending at each position either extends the previous one or starts fresh: current = max(x, current + x).

Show solution
Java
public class MaxSubarray {
    static int maxSubarray(int[] v) {
        int current = v[0];
        int best = v[0];
        for (int i = 1; i < v.length; i++) {
            current = Math.max(v[i], current + v[i]);
            best = Math.max(best, current);
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(maxSubarray(new int[] {-2, 1, -3, 4, -1, 2, 1, -5, 4}));
        System.out.println(maxSubarray(new int[] {-3, -1, -2}));
    }
}
Output
6
-1

O(n) time, O(1) space. Starting from the first element (not 0) handles all-negative arrays.

Challenge 6: Merge Two Sorted Arrays#

Merge Sorted Arrays

Merge two sorted arrays into one sorted array without calling a sort method.

Show hint

Walk both arrays with two indexes, always taking the smaller current element.

Show solution
Java
import java.util.Arrays;

public class Merge {
    static int[] merge(int[] a, int[] b) {
        int[] out = new int[a.length + b.length];
        int i = 0, j = 0, k = 0;
        while (i < a.length && j < b.length) {
            out[k++] = a[i] <= b[j] ? a[i++] : b[j++];
        }
        while (i < a.length) out[k++] = a[i++];
        while (j < b.length) out[k++] = b[j++];
        return out;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(merge(new int[] {1, 4, 9}, new int[] {2, 3, 10, 12})));
    }
}
Output
[1, 2, 3, 4, 9, 10, 12]

O(n + m) time.

Binary Search

Return the index of target in a sorted array, or -1, iteratively.

Show hint

Keep a range [low, high]; compare with the middle and discard half. Compute the middle as low + (high - low) / 2.

Show solution
Java
public class Search {
    static int binarySearch(int[] a, int target) {
        int low = 0;
        int high = a.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (a[mid] == target) return mid;
            if (a[mid] < target) low = mid + 1;
            else high = mid - 1;
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] a = {3, 8, 15, 23, 42, 57, 91};
        System.out.println(binarySearch(a, 42) + " " + binarySearch(a, 3) + " " + binarySearch(a, 50));
    }
}
Output
4 0 -1

O(log n) time. Arrays.binarySearch is the library version (it returns a negative insertion point when the value is missing).

Challenge 8: Longest Substring Without Repeating Characters#

Longest Unique Substring

Return the length of the longest substring without repeating characters. "abcabcbb" → 3, "pwwkew" → 3.

Show hint

Use a sliding window. Remember the last index of each character; when a repeat appears inside the window, move the window's left edge past it.

Show solution
Java
import java.util.HashMap;
import java.util.Map;

public class LongestUnique {
    static int longestUnique(String s) {
        Map<Character, Integer> last = new HashMap<>();
        int best = 0;
        int left = 0;
        for (int right = 0; right < s.length(); right++) {
            char c = s.charAt(right);
            Integer prev = last.get(c);
            if (prev != null && prev >= left) {
                left = prev + 1;
            }
            last.put(c, right);
            best = Math.max(best, right - left + 1);
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(longestUnique("abcabcbb") + " " + longestUnique("pwwkew") + " "
                + longestUnique("bbbb") + " " + longestUnique(""));
    }
}
Output
3 3 1 0

O(n) time.

Challenge 9: Reverse the Words in a Sentence#

Reverse Words

Reverse the words in " the sky is blue ", giving "blue is sky the".

Show hint

strip() then split("\\s+") gives the words without empty strings.

Show solution
Java
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ReverseWords {
    public static void main(String[] args) {
        String s = "  the sky   is blue ";
        List<String> words = Arrays.asList(s.strip().split("\\s+"));
        Collections.reverse(words);
        System.out.println("[" + String.join(" ", words) + "]");
    }
}
Output
[blue is sky the]

O(n) time and space.

Challenge 10: LRU Cache#

LRU Cache

Implement a least-recently-used cache with a fixed capacity: get returns a value (or -1) and marks it as recently used; put adds a value and evicts the least recently used entry when full.

Show hint

LinkedHashMap can keep entries in access order (third constructor argument true) and lets you override removeEldestEntry.

Show solution
Java
import java.util.LinkedHashMap;
import java.util.Map;

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;
    }
}

public class LruDemo {
    public static void main(String[] args) {
        LRUCache<Integer, Integer> cache = new LRUCache<>(2);
        cache.put(1, 10);
        cache.put(2, 20);
        System.out.print(cache.get(1) + " ");                    // 1 is now most recent
        cache.put(3, 30);                                       // evicts 2
        System.out.print(cache.getOrDefault(2, -1) + " " + cache.get(3) + " ");
        cache.put(1, 11);
        cache.put(4, 40);                                       // evicts 3
        System.out.println(cache.getOrDefault(3, -1) + " " + cache.get(1) + " " + cache.get(4));
    }
}
Output
10 -1 30 -1 11 40

All operations are O(1). In an interview you may be asked to build it yourself from a HashMap plus a doubly linked list; this version shows you know the library.

How to approach a coding interview#

  1. Clarify the input size, edge cases (empty, duplicates, negatives) and the expected output.
  2. Start simple: describe a brute-force solution and its complexity, then improve it.
  3. Pick a technique: hashing, two pointers, sliding window, stack, binary search, sorting or dynamic programming.
  4. Write clean Java: clear names, the right collection type, and standard library helpers.
  5. Test out loud with a normal case and an edge case before saying you are done.

Finished this lesson?