Java Coding

Coding problems with optimized solutions, edge-case handling, complexity analysis, and JUnit 5 test cases.

Overview #

This chapter covers 25 essential Java coding problems that Senior QA Engineers encounter in technical interviews. Unlike pure software engineering interviews, QA coding questions emphasize testability, edge-case awareness, defensive programming, and clear communication of your thought process.

What Interviewers Evaluate

Dimension What They Watch For
Correctness Does the code handle all inputs, including edge cases?
Clarity Can a teammate read and maintain this code?
Testing Mindset Do you naturally think about what could go wrong?
Complexity Awareness Can you articulate time/space tradeoffs?
Communication Do you narrate your approach before coding?

How to Use This Chapter

  1. Read the problem statement — pause and think before reading the solution
  2. Write your own solution — then compare with the optimized version
  3. Study the edge cases — these are what separate senior from mid-level candidates
  4. Practice narration — say your thought process out loud
  5. Run the unit tests — modify them to add your own scenarios

Prerequisites

  • Java 11+ (LTS recommended)
  • JUnit 5 (Jupiter)
  • Basic familiarity with Collections Framework

Q1How Would You Reverse a String Safely? #

Problem Statement

Write a method that reverses a string, handling null input, empty strings, Unicode surrogate pairs, and whitespace-only strings without throwing exceptions.

Optimized Solution

public class StringReverser {

    /**
     * Reverses a string safely, handling null, empty, and Unicode surrogate pairs.
     *
     * @param input the string to reverse (nullable)
     * @return reversed string, or null if input is null
     */
    public static String reverse(String input) {
        if (input == null) {
            return null;
        }
        if (input.length() <= 1) {
            return input;
        }
        // StringBuilder.reverse() handles surrogate pairs correctly
        return new StringBuilder(input).reverse().toString();
    }

    /**
     * Reverses a string manually — useful to demonstrate algorithm knowledge.
     */
    public static String reverseManual(String input) {
        if (input == null) {
            return null;
        }
        char[] chars = input.toCharArray();
        int left = 0;
        int right = chars.length - 1;

        while (left < right) {
            // Handle surrogate pairs
            if (Character.isHighSurrogate(chars[left]) && left + 1 < right) {
                // Swap the pair as a unit
                char highLeft = chars[left];
                char lowLeft = chars[left + 1];
                chars[left] = chars[right - 1];
                chars[left + 1] = chars[right];
                chars[right - 1] = highLeft;
                chars[right] = lowLeft;
                left += 2;
                right -= 2;
            } else {
                char temp = chars[left];
                chars[left] = chars[right];
                chars[right] = temp;
                left++;
                right--;
            }
        }
        return new String(chars);
    }
}

Time/Space Complexity

  • Time Complexity: O(n) — we traverse the string once where n is the length
  • Space Complexity: O(n) — StringBuilder creates a new character array internally

Edge Cases

Case Input Expected Output
Null null null
Empty "" ""
Single char "a" "a"
Whitespace " " " "
Unicode emoji "hello 🌍" "🌍 olleh"
Palindrome "racecar" "racecar"

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.NullSource;

import static org.junit.jupiter.api.Assertions.*;

class StringReverserTest {

    @Test
    @DisplayName("Null input returns null")
    void shouldReturnNullForNullInput() {
        assertNull(StringReverser.reverse(null));
    }

    @Test
    @DisplayName("Empty string returns empty")
    void shouldReturnEmptyForEmptyInput() {
        assertEquals("", StringReverser.reverse(""));
    }

    @ParameterizedTest
    @CsvSource({
        "hello, olleh",
        "a, a",
        "ab, ba",
        "racecar, racecar"
    })
    @DisplayName("Standard reversals work correctly")
    void shouldReverseStandardStrings(String input, String expected) {
        assertEquals(expected, StringReverser.reverse(input));
    }

    @Test
    @DisplayName("Whitespace-only string preserves length")
    void shouldHandleWhitespaceOnly() {
        String result = StringReverser.reverse("   ");
        assertEquals(3, result.length());
        assertEquals("   ", result);
    }

    @Test
    @DisplayName("Unicode surrogate pairs handled correctly")
    void shouldHandleSurrogatePairs() {
        String emoji = "A\uD83C\uDF0DB"; // A🌍B
        String reversed = StringReverser.reverse(emoji);
        assertEquals("B\uD83C\uDF0DA", reversed); // B🌍A
    }
}

Common Mistakes

  1. Not handling null — throws NullPointerException immediately
  2. Using char array swap without surrogate pair awareness — corrupts emoji/CJK characters
  3. Creating unnecessary intermediate strings — poor space efficiency
  4. Forgetting that String is immutable — trying to modify in place

Interview Narration Tips

"First, I'd clarify edge cases: what should happen with null? Empty string? Then I'd mention that StringBuilder.reverse() is the idiomatic Java approach and it handles surrogate pairs. If asked to implement manually, I'd use a two-pointer swap while checking for surrogate pairs."

Follow-up Questions

  • How would you reverse words in a sentence without reversing characters?
  • What's the difference between StringBuilder and StringBuffer for this?
  • How would you test this with property-based testing?

Q2How Would You Test Whether a String Is a Palindrome? #

Problem Statement

Write a method that checks if a string is a palindrome, ignoring case and non-alphanumeric characters. Handle null and empty inputs gracefully.

Optimized Solution

public class PalindromeChecker {

    /**
     * Checks if a string is a palindrome, ignoring case and non-alphanumeric chars.
     *
     * @param input the string to check (nullable)
     * @return true if palindrome, false otherwise; null/empty returns true
     */
    public static boolean isPalindrome(String input) {
        if (input == null || input.isEmpty()) {
            return true; // debatable — clarify with interviewer
        }

        int left = 0;
        int right = input.length() - 1;

        while (left < right) {
            // Skip non-alphanumeric from left
            while (left < right && !Character.isLetterOrDigit(input.charAt(left))) {
                left++;
            }
            // Skip non-alphanumeric from right
            while (left < right && !Character.isLetterOrDigit(input.charAt(right))) {
                right--;
            }

            if (Character.toLowerCase(input.charAt(left)) !=
                Character.toLowerCase(input.charAt(right))) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }

    /**
     * Strict palindrome check — considers all characters including spaces.
     */
    public static boolean isStrictPalindrome(String input) {
        if (input == null || input.isEmpty()) {
            return true;
        }
        String reversed = new StringBuilder(input).reverse().toString();
        return input.equals(reversed);
    }
}

Time/Space Complexity

  • Time Complexity: O(n) — single pass with two pointers
  • Space Complexity: O(1) — no additional data structures (in-place comparison)

Edge Cases

Case Input Expected
Null null true
Empty "" true
Single char "a" true
With punctuation "A man, a plan, a canal: Panama" true
Numeric "12321" true
Not palindrome "hello" false
All special chars "!@#$%" true

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

import static org.junit.jupiter.api.Assertions.*;

class PalindromeCheckerTest {

    @ParameterizedTest
    @ValueSource(strings = {"racecar", "RaceCar", "A man, a plan, a canal: Panama", "12321", ""})
    @DisplayName("Valid palindromes return true")
    void shouldReturnTrueForPalindromes(String input) {
        assertTrue(PalindromeChecker.isPalindrome(input));
    }

    @ParameterizedTest
    @ValueSource(strings = {"hello", "ab", "palindrome"})
    @DisplayName("Non-palindromes return false")
    void shouldReturnFalseForNonPalindromes(String input) {
        assertFalse(PalindromeChecker.isPalindrome(input));
    }

    @Test
    @DisplayName("Null input returns true")
    void shouldReturnTrueForNull() {
        assertTrue(PalindromeChecker.isPalindrome(null));
    }

    @Test
    @DisplayName("String with only special characters is palindrome")
    void shouldHandleSpecialCharsOnly() {
        assertTrue(PalindromeChecker.isPalindrome("!@#$%"));
    }

    @Test
    @DisplayName("Mixed case palindrome detected")
    void shouldIgnoreCase() {
        assertTrue(PalindromeChecker.isPalindrome("Aba"));
    }
}

Common Mistakes

  1. Allocating a new reversed string — wastes O(n) space when O(1) is possible
  2. Not skipping non-alphanumeric characters — fails classic interview examples
  3. Using == instead of comparing lowercase — case-sensitive comparison fails
  4. Off-by-one error — using <= instead of < in the while loop

Interview Narration Tips

"I'd first ask: should we ignore case and punctuation? The classic LeetCode version does. I'll use two pointers converging from both ends, skipping non-alphanumeric characters, and comparing lowercase versions. This gives O(1) space."

Follow-up Questions

  • How would you find the longest palindromic substring?
  • What if the input is a linked list instead of a string?
  • How would you make this work with Unicode normalization?

Q3How Would You Count Duplicate Characters? #

Problem Statement

Given a string, return a map of characters that appear more than once along with their counts. Handle null, empty strings, and decide on case sensitivity.

Optimized Solution

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class DuplicateCounter {

    /**
     * Counts characters that appear more than once (case-insensitive).
     *
     * @param input the string to analyze (nullable)
     * @return map of duplicate characters to their counts; empty map for null/empty
     */
    public static Map<Character, Integer> countDuplicates(String input) {
        if (input == null || input.isEmpty()) {
            return new LinkedHashMap<>();
        }

        Map<Character, Integer> charCount = new LinkedHashMap<>();
        for (char c : input.toLowerCase().toCharArray()) {
            charCount.merge(c, 1, Integer::sum);
        }

        // Filter to only duplicates
        charCount.entrySet().removeIf(entry -> entry.getValue() < 2);
        return charCount;
    }

    /**
     * Case-sensitive version using streams.
     */
    public static Map<Character, Long> countDuplicatesStream(String input) {
        if (input == null || input.isEmpty()) {
            return new LinkedHashMap<>();
        }

        return input.chars()
                .mapToObj(c -> (char) c)
                .collect(Collectors.groupingBy(c -> c, LinkedHashMap::new, Collectors.counting()))
                .entrySet().stream()
                .filter(e -> e.getValue() > 1)
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (a, b) -> a,
                        LinkedHashMap::new));
    }
}

Time/Space Complexity

  • Time Complexity: O(n) — single pass to count, then one pass to filter
  • Space Complexity: O(k) — where k is the number of unique characters (bounded by alphabet size, so effectively O(1) for ASCII)

Edge Cases

Case Input Expected
Null null {} (empty map)
Empty "" {}
No duplicates "abc" {}
All same "aaaa" {a=4}
Mixed case "AaBb" {a=2, b=2}
With spaces "hello world" {l=3, o=2}

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;

import java.util.Map;

import static org.junit.jupiter.api.Assertions.*;

class DuplicateCounterTest {

    @Test
    @DisplayName("Null returns empty map")
    void shouldReturnEmptyForNull() {
        assertTrue(DuplicateCounter.countDuplicates(null).isEmpty());
    }

    @Test
    @DisplayName("No duplicates returns empty map")
    void shouldReturnEmptyForNoDuplicates() {
        assertTrue(DuplicateCounter.countDuplicates("abc").isEmpty());
    }

    @Test
    @DisplayName("Counts duplicates correctly")
    void shouldCountDuplicates() {
        Map<Character, Integer> result = DuplicateCounter.countDuplicates("programming");
        assertEquals(2, result.get('r'));
        assertEquals(2, result.get('g'));
        assertEquals(2, result.get('m'));
        assertNull(result.get('p')); // appears only once
    }

    @Test
    @DisplayName("Case insensitive counting")
    void shouldBeCaseInsensitive() {
        Map<Character, Integer> result = DuplicateCounter.countDuplicates("AaBbCc");
        assertEquals(2, result.get('a'));
        assertEquals(2, result.get('b'));
        assertEquals(2, result.get('c'));
    }

    @Test
    @DisplayName("Handles spaces as characters")
    void shouldCountSpaces() {
        Map<Character, Integer> result = DuplicateCounter.countDuplicates("a b a b");
        assertEquals(2, result.get('a'));
        assertEquals(2, result.get('b'));
        assertEquals(3, result.get(' '));
    }
}

Common Mistakes

  1. Returning all characters instead of only duplicates — misreading the requirement
  2. Not specifying case sensitivity upfront — clarify with interviewer
  3. Using HashMap when order matters — use LinkedHashMap for deterministic output
  4. Forgetting merge() exists — writing verbose if/else for counting

Interview Narration Tips

"I'd ask: case-sensitive or not? Should spaces count? Then I'd use a LinkedHashMap to preserve insertion order, count all characters in one pass, then filter to those with count > 1. Time is O(n), space is O(1) for bounded character sets."

Follow-up Questions

  • How would you count duplicate words instead of characters?
  • What if the string is 1TB — how would you parallelize?
  • How would you unit test the ordering guarantee?

Q4How Would You Find the First Non-Repeating Character? #

Problem Statement

Given a string, find and return the first character that appears exactly once. Return a sentinel value or Optional if no such character exists.

Optimized Solution

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;

public class FirstUniqueCharFinder {

    /**
     * Finds the first non-repeating character using LinkedHashMap.
     *
     * @param input the string to search (nullable)
     * @return Optional containing the first unique char, or empty
     */
    public static Optional<Character> findFirstUnique(String input) {
        if (input == null || input.isEmpty()) {
            return Optional.empty();
        }

        LinkedHashMap<Character, Integer> charCount = new LinkedHashMap<>();
        for (char c : input.toCharArray()) {
            charCount.merge(c, 1, Integer::sum);
        }

        return charCount.entrySet().stream()
                .filter(entry -> entry.getValue() == 1)
                .map(Map.Entry::getKey)
                .findFirst();
    }

    /**
     * Index-based approach — returns the index of first unique char.
     * Returns -1 if none found.
     */
    public static int findFirstUniqueIndex(String input) {
        if (input == null || input.isEmpty()) {
            return -1;
        }

        int[] frequency = new int[256]; // ASCII assumption
        for (char c : input.toCharArray()) {
            frequency[c]++;
        }

        for (int i = 0; i < input.length(); i++) {
            if (frequency[input.charAt(i)] == 1) {
                return i;
            }
        }
        return -1;
    }
}

Time/Space Complexity

  • Time Complexity: O(n) — two passes: one to build frequency, one to find first unique
  • Space Complexity: O(1) — bounded by character set size (256 for ASCII, or O(k) for Unicode)

Edge Cases

Case Input Expected
Null null Optional.empty()
Empty "" Optional.empty()
All duplicates "aabbcc" Optional.empty()
First char unique "abc" Optional.of('a')
Last char unique "aabbc" Optional.of('c')
Single char "z" Optional.of('z')

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;

import java.util.Optional;

import static org.junit.jupiter.api.Assertions.*;

class FirstUniqueCharFinderTest {

    @Test
    @DisplayName("Null returns empty Optional")
    void shouldReturnEmptyForNull() {
        assertEquals(Optional.empty(), FirstUniqueCharFinder.findFirstUnique(null));
    }

    @Test
    @DisplayName("All duplicates returns empty")
    void shouldReturnEmptyWhenAllDuplicates() {
        assertEquals(Optional.empty(), FirstUniqueCharFinder.findFirstUnique("aabbcc"));
    }

    @Test
    @DisplayName("Finds first unique in middle")
    void shouldFindFirstUniqueInMiddle() {
        assertEquals(Optional.of('b'), FirstUniqueCharFinder.findFirstUnique("aabccd"));
    }

    @Test
    @DisplayName("Single character is unique")
    void shouldReturnSingleChar() {
        assertEquals(Optional.of('x'), FirstUniqueCharFinder.findFirstUnique("x"));
    }

    @Test
    @DisplayName("Index-based method returns correct index")
    void shouldReturnCorrectIndex() {
        assertEquals(2, FirstUniqueCharFinder.findFirstUniqueIndex("aabccd"));
        assertEquals(-1, FirstUniqueCharFinder.findFirstUniqueIndex("aabb"));
    }
}

Common Mistakes

  1. Using HashMap (unordered) — loses insertion order, can't find "first"
  2. Returning null instead of Optional — non-idiomatic, error-prone
  3. Single pass approach that doesn't work — you need frequency info before deciding
  4. Assuming ASCII — document the assumption or handle full Unicode

Interview Narration Tips

"The key insight is that we need two passes: first to count frequencies, then to find the first character with frequency 1. LinkedHashMap preserves insertion order so we iterate entries in order. Alternatively, an array of size 256 works for ASCII and is faster."

Follow-up Questions

  • What if the string is a stream and you can only read it once?
  • How would you adapt this for a case-insensitive version?
  • What's the tradeoff between the array and LinkedHashMap approach?

Q5How Would You Detect Duplicate IDs? #

Problem Statement

Given a list of objects (e.g., test results, API responses), detect and return any duplicate IDs. This is a common QA scenario when validating data integrity.

Optimized Solution

import java.util.*;
import java.util.stream.Collectors;

public class DuplicateIdDetector {

    /**
     * Finds duplicate IDs in a list.
     *
     * @param ids list of IDs (nullable, may contain nulls)
     * @return set of IDs that appear more than once
     */
    public static <T> Set<T> findDuplicateIds(List<T> ids) {
        if (ids == null || ids.isEmpty()) {
            return Collections.emptySet();
        }

        Set<T> seen = new HashSet<>();
        Set<T> duplicates = new LinkedHashSet<>(); // preserve discovery order

        for (T id : ids) {
            if (id == null) {
                continue; // skip nulls or handle as needed
            }
            if (!seen.add(id)) {
                duplicates.add(id);
            }
        }
        return duplicates;
    }

    /**
     * Finds duplicates with their indices — useful for debugging test data.
     */
    public static <T> Map<T, List<Integer>> findDuplicatesWithIndices(List<T> ids) {
        if (ids == null || ids.isEmpty()) {
            return Collections.emptyMap();
        }

        Map<T, List<Integer>> indexMap = new LinkedHashMap<>();
        for (int i = 0; i < ids.size(); i++) {
            T id = ids.get(i);
            if (id != null) {
                indexMap.computeIfAbsent(id, k -> new ArrayList<>()).add(i);
            }
        }

        // Filter to only duplicates
        indexMap.entrySet().removeIf(entry -> entry.getValue().size() < 2);
        return indexMap;
    }

    /**
     * Stream-based approach for functional style.
     */
    public static <T> Set<T> findDuplicatesStream(List<T> ids) {
        if (ids == null) return Collections.emptySet();

        return ids.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.groupingBy(id -> id, Collectors.counting()))
                .entrySet().stream()
                .filter(e -> e.getValue() > 1)
                .map(Map.Entry::getKey)
                .collect(Collectors.toSet());
    }
}

Time/Space Complexity

  • Time Complexity: O(n) — single pass through the list
  • Space Complexity: O(n) — storing all unique IDs in the HashSet

Edge Cases

Case Input Expected
Null list null empty set
Empty list [] empty set
No duplicates [1, 2, 3] empty set
All same [1, 1, 1] {1}
Nulls in list [1, null, 1] {1}
Strings ["a", "b", "a"] {"a"}

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;

import java.util.*;

import static org.junit.jupiter.api.Assertions.*;

class DuplicateIdDetectorTest {

    @Test
    @DisplayName("Null list returns empty set")
    void shouldHandleNullList() {
        assertTrue(DuplicateIdDetector.findDuplicateIds(null).isEmpty());
    }

    @Test
    @DisplayName("No duplicates returns empty set")
    void shouldReturnEmptyWhenNoDuplicates() {
        List<Integer> ids = Arrays.asList(1, 2, 3, 4, 5);
        assertTrue(DuplicateIdDetector.findDuplicateIds(ids).isEmpty());
    }

    @Test
    @DisplayName("Detects integer duplicates")
    void shouldFindIntegerDuplicates() {
        List<Integer> ids = Arrays.asList(1, 2, 3, 2, 4, 1);
        Set<Integer> duplicates = DuplicateIdDetector.findDuplicateIds(ids);
        assertEquals(Set.of(1, 2), duplicates);
    }

    @Test
    @DisplayName("Handles null elements gracefully")
    void shouldSkipNullElements() {
        List<String> ids = Arrays.asList("a", null, "b", "a", null);
        Set<String> duplicates = DuplicateIdDetector.findDuplicateIds(ids);
        assertEquals(Set.of("a"), duplicates);
    }

    @Test
    @DisplayName("Finds duplicates with indices")
    void shouldReturnIndicesOfDuplicates() {
        List<String> ids = Arrays.asList("x", "y", "x", "z", "y");
        Map<String, List<Integer>> result = DuplicateIdDetector.findDuplicatesWithIndices(ids);
        assertEquals(Arrays.asList(0, 2), result.get("x"));
        assertEquals(Arrays.asList(1, 4), result.get("y"));
    }
}

Common Mistakes

  1. Using contains() on a List — O(n²) total time instead of O(n) with HashSet
  2. Not handling null elements — NullPointerException in HashSet operations
  3. Returning indices instead of IDs — misunderstanding the requirement
  4. Modifying the input list — side effects that break caller assumptions

Interview Narration Tips

"This is a classic QA scenario — validating uniqueness constraints in test data or API responses. I'd use a HashSet for O(1) lookups. The trick is: if set.add() returns false, the element was already there — that's our duplicate. I'd also offer a version that returns indices for debugging."

Follow-up Questions

  • How would you detect duplicates in a database table with millions of rows?
  • What if IDs are composite (multiple fields)?
  • How would you integrate this into an API test framework?

Q6How Would You Validate Balanced Parentheses? #

Problem Statement

Write a method that checks if a string has balanced brackets: (), [], {}. This models validation of JSON structures, code syntax, or nested test configurations.

Optimized Solution

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Map;

public class BalancedParentheses {

    private static final Map<Character, Character> BRACKET_PAIRS = Map.of(
            ')', '(',
            ']', '[',
            '}', '{'
    );

    /**
     * Validates that all brackets in the string are balanced.
     *
     * @param input string to validate (nullable)
     * @return true if balanced or no brackets present
     */
    public static boolean isBalanced(String input) {
        if (input == null || input.isEmpty()) {
            return true;
        }

        Deque<Character> stack = new ArrayDeque<>();

        for (char c : input.toCharArray()) {
            if (BRACKET_PAIRS.containsValue(c)) {
                // Opening bracket
                stack.push(c);
            } else if (BRACKET_PAIRS.containsKey(c)) {
                // Closing bracket
                if (stack.isEmpty() || !stack.pop().equals(BRACKET_PAIRS.get(c))) {
                    return false;
                }
            }
            // Non-bracket characters are ignored
        }

        return stack.isEmpty();
    }
}

Time/Space Complexity

  • Time Complexity: O(n) — single pass through the string
  • Space Complexity: O(n) — worst case all opening brackets pushed to stack

Edge Cases

Case Input Expected
Null null true
Empty "" true
Simple valid "()" true
Nested "{[()]}" true
Unmatched open "(((" false
Unmatched close ")))" false
Wrong order "(]" false
Mixed content "if (a[0] == {b})" true
Single bracket "(" false

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

import static org.junit.jupiter.api.Assertions.*;

class BalancedParenthesesTest {

    @ParameterizedTest
    @ValueSource(strings = {"()", "[]", "{}", "{[()]}", "a(b)c[d]", ""})
    @DisplayName("Balanced inputs return true")
    void shouldReturnTrueForBalanced(String input) {
        assertTrue(BalancedParentheses.isBalanced(input));
    }

    @ParameterizedTest
    @ValueSource(strings = {"(", ")", "([)", "{[}", "((())", "())("})
    @DisplayName("Unbalanced inputs return false")
    void shouldReturnFalseForUnbalanced(String input) {
        assertFalse(BalancedParentheses.isBalanced(input));
    }

    @Test
    @DisplayName("Null input returns true")
    void shouldReturnTrueForNull() {
        assertTrue(BalancedParentheses.isBalanced(null));
    }

    @Test
    @DisplayName("String without brackets returns true")
    void shouldReturnTrueForNoBrackets() {
        assertTrue(BalancedParentheses.isBalanced("hello world"));
    }
}

Common Mistakes

  1. Only counting open/close without matching type — "(]" wrongly passes
  2. Using Stack class instead of ArrayDeque — Stack is legacy and synchronized
  3. Not checking stack.isEmpty() before pop() — EmptyStackException
  4. Forgetting to check stack is empty at end — "(()" wrongly passes

Interview Narration Tips

"Classic stack problem. I'd use a Deque as my stack. For each character: if it's an opener, push it. If it's a closer, pop and verify the match. At the end, the stack must be empty. I'd use a Map for bracket pairs to keep it extensible."

Follow-up Questions

  • How would you report the position of the first mismatch?
  • How would you extend this to validate HTML tags?
  • What's the maximum nesting depth (stack high-water mark)?

Q7How Would You Merge Overlapping Intervals? #

Problem Statement

Given a list of intervals [start, end], merge all overlapping intervals. This models test schedule optimization, time-window deduplication, or log aggregation.

Optimized Solution

import java.util.*;

public class IntervalMerger {

    /**
     * Merges overlapping intervals.
     *
     * @param intervals list of [start, end] pairs (nullable)
     * @return merged intervals sorted by start time
     */
    public static List<int[]> merge(List<int[]> intervals) {
        if (intervals == null || intervals.isEmpty()) {
            return new ArrayList<>();
        }

        // Sort by start time
        intervals.sort(Comparator.comparingInt(a -> a[0]));

        List<int[]> merged = new ArrayList<>();
        int[] current = intervals.get(0);
        merged.add(current);

        for (int i = 1; i < intervals.size(); i++) {
            int[] next = intervals.get(i);
            if (next[0] <= current[1]) {
                // Overlapping — extend current interval
                current[1] = Math.max(current[1], next[1]);
            } else {
                // No overlap — start new interval
                current = next;
                merged.add(current);
            }
        }

        return merged;
    }

    /**
     * Checks if two intervals overlap.
     */
    public static boolean overlaps(int[] a, int[] b) {
        return a[0] <= b[1] && b[0] <= a[1];
    }
}

Time/Space Complexity

  • Time Complexity: O(n log n) — dominated by the sort step
  • Space Complexity: O(n) — output list in worst case (no overlaps)

Edge Cases

Case Input Expected
Null null []
Empty [] []
Single [[1,3]] [[1,3]]
No overlap [[1,2],[4,5]] [[1,2],[4,5]]
Full overlap [[1,5],[2,3]] [[1,5]]
Adjacent [[1,2],[2,3]] [[1,3]]
All merge [[1,4],[2,5],[3,6]] [[1,6]]

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;

import java.util.*;

import static org.junit.jupiter.api.Assertions.*;

class IntervalMergerTest {

    @Test
    @DisplayName("Null returns empty list")
    void shouldHandleNull() {
        assertTrue(IntervalMerger.merge(null).isEmpty());
    }

    @Test
    @DisplayName("Non-overlapping intervals unchanged")
    void shouldKeepNonOverlapping() {
        List<int[]> input = new ArrayList<>(Arrays.asList(
                new int[]{1, 2}, new int[]{4, 5}));
        List<int[]> result = IntervalMerger.merge(input);
        assertEquals(2, result.size());
    }

    @Test
    @DisplayName("Overlapping intervals merged")
    void shouldMergeOverlapping() {
        List<int[]> input = new ArrayList<>(Arrays.asList(
                new int[]{1, 3}, new int[]{2, 6}, new int[]{8, 10}));
        List<int[]> result = IntervalMerger.merge(input);
        assertEquals(2, result.size());
        assertArrayEquals(new int[]{1, 6}, result.get(0));
        assertArrayEquals(new int[]{8, 10}, result.get(1));
    }

    @Test
    @DisplayName("Adjacent intervals merged (touching boundaries)")
    void shouldMergeAdjacent() {
        List<int[]> input = new ArrayList<>(Arrays.asList(
                new int[]{1, 2}, new int[]{2, 3}));
        List<int[]> result = IntervalMerger.merge(input);
        assertEquals(1, result.size());
        assertArrayEquals(new int[]{1, 3}, result.get(0));
    }

    @Test
    @DisplayName("Unsorted input handled correctly")
    void shouldHandleUnsortedInput() {
        List<int[]> input = new ArrayList<>(Arrays.asList(
                new int[]{5, 7}, new int[]{1, 3}, new int[]{2, 4}));
        List<int[]> result = IntervalMerger.merge(input);
        assertEquals(2, result.size());
        assertArrayEquals(new int[]{1, 4}, result.get(0));
    }
}

Common Mistakes

  1. Not sorting first — comparing non-adjacent intervals incorrectly
  2. Using == instead of <= for overlap check — missing touching intervals
  3. Not updating end with Math.max — fails when one interval contains another
  4. Modifying input list without copying — side effects

Interview Narration Tips

"First sort by start time. Then iterate: if the next interval's start is <= current end, they overlap, so extend. Otherwise start a new group. Sorting dominates at O(n log n). I'd mention this maps to real QA scenarios like merging test execution windows."

Follow-up Questions

  • How would you insert a new interval into an already-merged list?
  • What if intervals represent test environments being reserved — how would you find gaps?
  • How would you handle intervals with timestamps instead of integers?

Q8How Would You Implement Binary Search? #

Problem Statement

Implement binary search on a sorted array. Return the index of the target, or -1 if not found. This tests your ability to write loop invariants correctly.

Optimized Solution

public class BinarySearch {

    /**
     * Standard binary search on a sorted array.
     *
     * @param arr    sorted array (nullable)
     * @param target value to find
     * @return index of target, or -1 if not found
     */
    public static int search(int[] arr, int target) {
        if (arr == null || arr.length == 0) {
            return -1;
        }

        int left = 0;
        int right = arr.length - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2; // prevents overflow

            if (arr[mid] == target) {
                return mid;
            } else if (arr[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }

    /**
     * Finds the first occurrence of target (for arrays with duplicates).
     */
    public static int searchFirst(int[] arr, int target) {
        if (arr == null || arr.length == 0) {
            return -1;
        }

        int left = 0;
        int right = arr.length - 1;
        int result = -1;

        while (left <= right) {
            int mid = left + (right - left) / 2;

            if (arr[mid] == target) {
                result = mid;
                right = mid - 1; // continue searching left
            } else if (arr[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return result;
    }
}

Time/Space Complexity

  • Time Complexity: O(log n) — halving the search space each iteration
  • Space Complexity: O(1) — iterative approach uses constant space

Edge Cases

Case Input Expected
Null array null, 5 -1
Empty array [], 5 -1
Single element found [5], 5 0
Single element not found [3], 5 -1
First element [1,2,3,4,5], 1 0
Last element [1,2,3,4,5], 5 4
Not present [1,2,3,4,5], 6 -1
Duplicates [1,2,2,2,3], 2 1 (first)

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;

import static org.junit.jupiter.api.Assertions.*;

class BinarySearchTest {

    @Test
    @DisplayName("Null array returns -1")
    void shouldReturnNegativeOneForNull() {
        assertEquals(-1, BinarySearch.search(null, 5));
    }

    @Test
    @DisplayName("Empty array returns -1")
    void shouldReturnNegativeOneForEmpty() {
        assertEquals(-1, BinarySearch.search(new int[]{}, 5));
    }

    @Test
    @DisplayName("Finds element in middle")
    void shouldFindMiddleElement() {
        assertEquals(2, BinarySearch.search(new int[]{1, 2, 3, 4, 5}, 3));
    }

    @Test
    @DisplayName("Finds first element")
    void shouldFindFirstElement() {
        assertEquals(0, BinarySearch.search(new int[]{1, 2, 3, 4, 5}, 1));
    }

    @Test
    @DisplayName("Finds last element")
    void shouldFindLastElement() {
        assertEquals(4, BinarySearch.search(new int[]{1, 2, 3, 4, 5}, 5));
    }

    @Test
    @DisplayName("Returns -1 for missing element")
    void shouldReturnNegativeOneForMissing() {
        assertEquals(-1, BinarySearch.search(new int[]{1, 2, 3, 4, 5}, 6));
    }

    @Test
    @DisplayName("searchFirst finds leftmost duplicate")
    void shouldFindFirstOccurrence() {
        assertEquals(1, BinarySearch.searchFirst(new int[]{1, 2, 2, 2, 3}, 2));
    }
}

Common Mistakes

  1. Using (left + right) / 2 — integer overflow for large arrays
  2. Using left < right instead of left <= right — misses single-element case
  3. Setting right = mid or left = mid — infinite loop
  4. Assuming array is sorted — not validating precondition

Interview Narration Tips

"Binary search looks simple but has subtle bugs. I always use left + (right - left) / 2 to prevent overflow. The loop condition is <= because both pointers are inclusive. After finding the target, if duplicates exist, I can continue searching left for the first occurrence."

Follow-up Questions

  • How would you find the insertion point (lower bound)?
  • How would you binary search a rotated sorted array?
  • When would you use Arrays.binarySearch() vs. writing your own?

Q9How Would You Find a Missing Number? #

Problem Statement

Given an array containing n distinct numbers from 0 to n, find the one number that is missing. This models detecting dropped test cases or missing sequence IDs in test reports.

Optimized Solution

public class MissingNumberFinder {

    /**
     * Finds the missing number using Gauss sum formula.
     *
     * @param nums array of n numbers from range [0, n] with one missing
     * @return the missing number
     */
    public static int findMissing(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int n = nums.length;
        long expectedSum = (long) n * (n + 1) / 2;
        long actualSum = 0;

        for (int num : nums) {
            actualSum += num;
        }

        return (int) (expectedSum - actualSum);
    }

    /**
     * XOR approach — avoids potential overflow for very large n.
     */
    public static int findMissingXor(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int xor = nums.length; // start with n
        for (int i = 0; i < nums.length; i++) {
            xor ^= i ^ nums[i];
        }
        return xor;
    }
}

Time/Space Complexity

  • Time Complexity: O(n) — single pass through the array
  • Space Complexity: O(1) — only constant variables used

Edge Cases

Case Input Expected
Null null 0
Empty [] 0
Missing 0 [1, 2, 3] 0
Missing last [0, 1, 2] 3
Missing middle [0, 1, 3] 2
Single element [0] 1
Large n [0..999999] minus one that number

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;

import static org.junit.jupiter.api.Assertions.*;

class MissingNumberFinderTest {

    @Test
    @DisplayName("Null array returns 0")
    void shouldReturnZeroForNull() {
        assertEquals(0, MissingNumberFinder.findMissing(null));
    }

    @Test
    @DisplayName("Missing number at start")
    void shouldFindMissingAtStart() {
        assertEquals(0, MissingNumberFinder.findMissing(new int[]{1, 2, 3}));
    }

    @Test
    @DisplayName("Missing number at end")
    void shouldFindMissingAtEnd() {
        assertEquals(3, MissingNumberFinder.findMissing(new int[]{0, 1, 2}));
    }

    @Test
    @DisplayName("Missing number in middle")
    void shouldFindMissingInMiddle() {
        assertEquals(2, MissingNumberFinder.findMissing(new int[]{0, 1, 3, 4}));
    }

    @Test
    @DisplayName("XOR approach matches sum approach")
    void xorShouldMatchSumApproach() {
        int[] nums = {0, 1, 3, 4, 5};
        assertEquals(
                MissingNumberFinder.findMissing(nums),
                MissingNumberFinder.findMissingXor(nums));
    }
}

Common Mistakes

  1. Integer overflow with sum formula — use long for intermediate calculation
  2. Sorting first — unnecessary O(n log n) when O(n) is possible
  3. Using a HashSet — works but wastes O(n) space
  4. Off-by-one on range — confusing [0,n] with [1,n]

Interview Narration Tips

"Two elegant O(n) time, O(1) space approaches: the Gauss sum formula (expected minus actual) or XOR (since x ^ x = 0). I'd use the sum approach for clarity but mention XOR avoids overflow for very large n. In QA, this maps to finding a dropped test case ID in a sequential suite."

Follow-up Questions

  • What if two numbers are missing?
  • What if the array has duplicates and one missing?
  • How would you find missing numbers in a large distributed dataset?

Q10How Would You Validate a State Transition? #

Problem Statement

Given a set of valid state transitions (e.g., for a workflow or test lifecycle), validate whether a sequence of states is legal. This models test status validation (e.g., PENDING → RUNNING → PASSED).

Optimized Solution

import java.util.*;

public class StateTransitionValidator {

    private final Map<String, Set<String>> validTransitions;

    public StateTransitionValidator(Map<String, Set<String>> validTransitions) {
        this.validTransitions = validTransitions != null
                ? validTransitions
                : Collections.emptyMap();
    }

    /**
     * Validates a sequence of state transitions.
     *
     * @param states ordered list of states
     * @return ValidationResult with success/failure and details
     */
    public ValidationResult validate(List<String> states) {
        if (states == null || states.size() <= 1) {
            return ValidationResult.success();
        }

        for (int i = 0; i < states.size() - 1; i++) {
            String from = states.get(i);
            String to = states.get(i + 1);

            if (from == null || to == null) {
                return ValidationResult.failure(i,
                        "Null state at position " + (from == null ? i : i + 1));
            }

            Set<String> allowed = validTransitions.get(from);
            if (allowed == null || !allowed.contains(to)) {
                return ValidationResult.failure(i,
                        String.format("Invalid transition: '%s' -> '%s' at position %d", from, to, i));
            }
        }
        return ValidationResult.success();
    }

    /**
     * Result object for validation — provides details on failure.
     */
    public static class ValidationResult {
        private final boolean valid;
        private final int failureIndex;
        private final String message;

        private ValidationResult(boolean valid, int failureIndex, String message) {
            this.valid = valid;
            this.failureIndex = failureIndex;
            this.message = message;
        }

        public static ValidationResult success() {
            return new ValidationResult(true, -1, "All transitions valid");
        }

        public static ValidationResult failure(int index, String message) {
            return new ValidationResult(false, index, message);
        }

        public boolean isValid() { return valid; }
        public int getFailureIndex() { return failureIndex; }
        public String getMessage() { return message; }
    }

    /**
     * Factory method for common test lifecycle states.
     */
    public static StateTransitionValidator testLifecycle() {
        Map<String, Set<String>> transitions = new HashMap<>();
        transitions.put("PENDING", Set.of("RUNNING", "SKIPPED"));
        transitions.put("RUNNING", Set.of("PASSED", "FAILED", "ERROR"));
        transitions.put("PASSED", Set.of("PENDING")); // re-run
        transitions.put("FAILED", Set.of("PENDING")); // retry
        transitions.put("ERROR", Set.of("PENDING"));
        transitions.put("SKIPPED", Set.of("PENDING"));
        return new StateTransitionValidator(transitions);
    }
}

Time/Space Complexity

  • Time Complexity: O(n) — one pass through the state sequence; each lookup is O(1)
  • Space Complexity: O(S) — where S is the number of states × average transitions per state

Edge Cases

Case Input States Expected
Null null valid
Empty [] valid
Single state ["PENDING"] valid
Valid sequence ["PENDING", "RUNNING", "PASSED"] valid
Invalid transition ["PENDING", "PASSED"] invalid
Unknown state ["PENDING", "UNKNOWN"] invalid
Null in list ["PENDING", null] invalid

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.BeforeEach;

import java.util.*;

import static org.junit.jupiter.api.Assertions.*;

class StateTransitionValidatorTest {

    private StateTransitionValidator validator;

    @BeforeEach
    void setUp() {
        validator = StateTransitionValidator.testLifecycle();
    }

    @Test
    @DisplayName("Valid transition sequence passes")
    void shouldPassValidSequence() {
        List<String> states = List.of("PENDING", "RUNNING", "PASSED");
        assertTrue(validator.validate(states).isValid());
    }

    @Test
    @DisplayName("Invalid transition detected")
    void shouldDetectInvalidTransition() {
        List<String> states = List.of("PENDING", "PASSED");
        var result = validator.validate(states);
        assertFalse(result.isValid());
        assertTrue(result.getMessage().contains("Invalid transition"));
    }

    @Test
    @DisplayName("Null list is valid")
    void shouldHandleNullList() {
        assertTrue(validator.validate(null).isValid());
    }

    @Test
    @DisplayName("Single state is valid")
    void shouldHandleSingleState() {
        assertTrue(validator.validate(List.of("PENDING")).isValid());
    }

    @Test
    @DisplayName("Retry path is valid")
    void shouldAllowRetryPath() {
        List<String> states = List.of("PENDING", "RUNNING", "FAILED", "PENDING", "RUNNING", "PASSED");
        assertTrue(validator.validate(states).isValid());
    }
}

Common Mistakes

  1. Hardcoding transitions — use a configurable map for reusability
  2. Only returning boolean — provide failure details for debugging
  3. Not handling unknown states — NPE when looking up transitions
  4. Checking only adjacent pairs — some candidates try to validate the entire graph

Interview Narration Tips

"I'd model this as a directed graph where nodes are states and edges are valid transitions. Store it in a Map<String, Set<String>>. Then validate by walking the sequence and checking each pair. I return a result object with failure details because in QA, you need to know where it broke."

Follow-up Questions

  • How would you visualize the state machine for documentation?
  • How would you detect unreachable states in the transition map?
  • How would you log invalid transitions in a test framework?

Q11How Would You Compare Two Arrays Ignoring Order? #

Problem Statement

Compare two arrays for equality regardless of element order. Handle duplicates correctly (i.e., [1,1,2] ≠ [1,2,2]). This is common when validating API responses where order isn't guaranteed.

Optimized Solution

import java.util.*;

public class ArrayComparator {

    /**
     * Compares two arrays ignoring order but respecting duplicate counts.
     *
     * @param arr1 first array (nullable)
     * @param arr2 second array (nullable)
     * @return true if arrays contain same elements with same frequencies
     */
    public static <T> boolean equalIgnoringOrder(T[] arr1, T[] arr2) {
        if (arr1 == arr2) return true;
        if (arr1 == null || arr2 == null) return false;
        if (arr1.length != arr2.length) return false;

        Map<T, Integer> frequencyMap = new HashMap<>();

        for (T item : arr1) {
            frequencyMap.merge(item, 1, Integer::sum);
        }

        for (T item : arr2) {
            int count = frequencyMap.getOrDefault(item, 0);
            if (count == 0) {
                return false; // element in arr2 not in arr1 (or exhausted)
            }
            frequencyMap.put(item, count - 1);
        }

        return true; // length check ensures no leftover in arr1
    }

    /**
     * Primitive int array version.
     */
    public static boolean equalIgnoringOrder(int[] arr1, int[] arr2) {
        if (arr1 == arr2) return true;
        if (arr1 == null || arr2 == null) return false;
        if (arr1.length != arr2.length) return false;

        Map<Integer, Integer> freq = new HashMap<>();
        for (int val : arr1) {
            freq.merge(val, 1, Integer::sum);
        }
        for (int val : arr2) {
            int count = freq.getOrDefault(val, 0);
            if (count == 0) return false;
            freq.put(val, count - 1);
        }
        return true;
    }
}

Time/Space Complexity

  • Time Complexity: O(n) — two passes through the arrays
  • Space Complexity: O(n) — frequency map stores up to n entries

Edge Cases

Case Array 1 Array 2 Expected
Both null null null true
One null [1] null false
Both empty [] [] true
Same order [1,2,3] [1,2,3] true
Different order [3,1,2] [1,2,3] true
Different dupes [1,1,2] [1,2,2] false
Different length [1,2] [1,2,3] false
With nulls [null,1] [1,null] true

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;

import static org.junit.jupiter.api.Assertions.*;

class ArrayComparatorTest {

    @Test
    @DisplayName("Same elements different order are equal")
    void shouldBeEqualDifferentOrder() {
        Integer[] a = {3, 1, 2};
        Integer[] b = {1, 2, 3};
        assertTrue(ArrayComparator.equalIgnoringOrder(a, b));
    }

    @Test
    @DisplayName("Different duplicate counts are not equal")
    void shouldDetectDifferentDuplicateCounts() {
        Integer[] a = {1, 1, 2};
        Integer[] b = {1, 2, 2};
        assertFalse(ArrayComparator.equalIgnoringOrder(a, b));
    }

    @Test
    @DisplayName("Both null returns true")
    void shouldHandleBothNull() {
        assertTrue(ArrayComparator.equalIgnoringOrder((Integer[]) null, null));
    }

    @Test
    @DisplayName("One null returns false")
    void shouldHandleOneNull() {
        assertFalse(ArrayComparator.equalIgnoringOrder(new Integer[]{1}, null));
    }

    @Test
    @DisplayName("Different lengths returns false quickly")
    void shouldReturnFalseForDifferentLengths() {
        Integer[] a = {1, 2};
        Integer[] b = {1, 2, 3};
        assertFalse(ArrayComparator.equalIgnoringOrder(a, b));
    }

    @Test
    @DisplayName("Primitive int arrays compared correctly")
    void shouldComparePrimitiveArrays() {
        assertTrue(ArrayComparator.equalIgnoringOrder(
                new int[]{5, 3, 1}, new int[]{1, 3, 5}));
    }
}

Common Mistakes

  1. Sorting both arrays — O(n log n) when O(n) is possible; also mutates input
  2. Using Set instead of frequency map — ignores duplicate counts
  3. Not checking lengths first — unnecessary work when lengths differ
  4. Not handling null elements in arrays — HashMap allows null keys

Interview Narration Tips

"The naive approach is to sort both arrays — O(n log n). Better: build a frequency map from the first array, then decrement for each element in the second. If any count goes below zero, they're different. The length check is an early exit optimization."

Follow-up Questions

  • How would you produce a diff showing which elements are extra/missing?
  • How would you compare two JSON arrays with nested objects?
  • What assertion library methods exist for this (e.g., AssertJ)?

Q12How Would You Group Anagrams? #

Problem Statement

Given a list of strings, group together strings that are anagrams of each other. This tests hash-based grouping and choosing the right key representation.

Optimized Solution

import java.util.*;
import java.util.stream.Collectors;

public class AnagramGrouper {

    /**
     * Groups strings that are anagrams of each other.
     *
     * @param words list of words (nullable, may contain nulls)
     * @return list of groups, each group is a list of anagrams
     */
    public static List<List<String>> groupAnagrams(List<String> words) {
        if (words == null || words.isEmpty()) {
            return new ArrayList<>();
        }

        Map<String, List<String>> groups = new HashMap<>();

        for (String word : words) {
            if (word == null) continue;

            String key = sortedKey(word);
            groups.computeIfAbsent(key, k -> new ArrayList<>()).add(word);
        }

        return new ArrayList<>(groups.values());
    }

    /**
     * Creates a canonical key by sorting characters.
     */
    private static String sortedKey(String word) {
        char[] chars = word.toLowerCase().toCharArray();
        Arrays.sort(chars);
        return new String(chars);
    }

    /**
     * Alternative: frequency-based key (avoids sorting for long strings).
     */
    private static String frequencyKey(String word) {
        int[] count = new int[26];
        for (char c : word.toLowerCase().toCharArray()) {
            if (c >= 'a' && c <= 'z') {
                count[c - 'a']++;
            }
        }
        return Arrays.toString(count);
    }
}

Time/Space Complexity

  • Time Complexity: O(n × k log k) — n words, each sorted in k log k where k is max word length
  • Space Complexity: O(n × k) — storing all words in groups

Edge Cases

Case Input Expected
Null null []
Empty list [] []
No anagrams ["abc", "xyz"] [["abc"], ["xyz"]]
All anagrams ["eat", "tea", "ate"] [["eat", "tea", "ate"]]
Mixed case ["Tea", "Eat"] grouped together
Empty strings ["", ""] [["", ""]]
Single char ["a", "a"] [["a", "a"]]

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;

import java.util.*;

import static org.junit.jupiter.api.Assertions.*;

class AnagramGrouperTest {

    @Test
    @DisplayName("Groups anagrams correctly")
    void shouldGroupAnagrams() {
        List<String> input = Arrays.asList("eat", "tea", "tan", "ate", "nat", "bat");
        List<List<String>> result = AnagramGrouper.groupAnagrams(input);

        assertEquals(3, result.size());

        // Verify group contents (order within groups may vary)
        Set<Set<String>> groupSets = new HashSet<>();
        for (List<String> group : result) {
            groupSets.add(new HashSet<>(group));
        }
        assertTrue(groupSets.contains(Set.of("eat", "tea", "ate")));
        assertTrue(groupSets.contains(Set.of("tan", "nat")));
        assertTrue(groupSets.contains(Set.of("bat")));
    }

    @Test
    @DisplayName("Null returns empty list")
    void shouldHandleNull() {
        assertTrue(AnagramGrouper.groupAnagrams(null).isEmpty());
    }

    @Test
    @DisplayName("No anagrams returns individual groups")
    void shouldHandleNoAnagrams() {
        List<String> input = Arrays.asList("abc", "xyz", "def");
        List<List<String>> result = AnagramGrouper.groupAnagrams(input);
        assertEquals(3, result.size());
    }

    @Test
    @DisplayName("Empty strings grouped together")
    void shouldGroupEmptyStrings() {
        List<String> input = Arrays.asList("", "");
        List<List<String>> result = AnagramGrouper.groupAnagrams(input);
        assertEquals(1, result.size());
        assertEquals(2, result.get(0).size());
    }
}

Common Mistakes

  1. Comparing every pair — O(n²) when grouping by key is O(n × k log k)
  2. Not normalizing case — "Tea" and "eat" should be in the same group
  3. Using the word itself as key — must use a canonical form (sorted chars)
  4. Forgetting that sorted key and frequency key have different performance profiles

Interview Narration Tips

"The key insight is: two strings are anagrams if and only if their sorted character sequences are identical. So I sort each word's characters to create a canonical key, then group by that key using a HashMap. For very long strings, a character frequency array as key avoids the sort."

Follow-up Questions

  • How would you find anagrams in a dictionary file with millions of words?
  • What's the tradeoff between sorted key vs. frequency key?
  • How would you test this with property-based testing?

Q13How Would You Remove Duplicates While Preserving Order? #

Problem Statement

Remove duplicate elements from a list while maintaining the original order of first appearances. This is common when deduplicating test data or API results.

Optimized Solution

import java.util.*;
import java.util.stream.Collectors;

public class OrderPreservingDeduplicator {

    /**
     * Removes duplicates preserving first-occurrence order.
     *
     * @param items list with potential duplicates (nullable)
     * @return new list with duplicates removed, order preserved
     */
    public static <T> List<T> deduplicate(List<T> items) {
        if (items == null || items.isEmpty()) {
            return new ArrayList<>();
        }

        Set<T> seen = new LinkedHashSet<>();
        for (T item : items) {
            seen.add(item); // LinkedHashSet maintains insertion order
        }
        return new ArrayList<>(seen);
    }

    /**
     * Stream-based approach using distinct().
     */
    public static <T> List<T> deduplicateStream(List<T> items) {
        if (items == null) return new ArrayList<>();
        return items.stream()
                .distinct()
                .collect(Collectors.toList());
    }

    /**
     * Deduplicate by a key extractor (e.g., remove duplicate objects by ID).
     */
    public static <T, K> List<T> deduplicateByKey(List<T> items,
                                                    java.util.function.Function<T, K> keyExtractor) {
        if (items == null || items.isEmpty()) {
            return new ArrayList<>();
        }

        Set<K> seenKeys = new HashSet<>();
        List<T> result = new ArrayList<>();

        for (T item : items) {
            K key = keyExtractor.apply(item);
            if (seenKeys.add(key)) {
                result.add(item);
            }
        }
        return result;
    }
}

Time/Space Complexity

  • Time Complexity: O(n) — single pass with O(1) HashSet operations
  • Space Complexity: O(n) — storing unique elements in the Set

Edge Cases

Case Input Expected
Null null []
Empty [] []
No duplicates [1, 2, 3] [1, 2, 3]
All same [1, 1, 1] [1]
Preserves order [3, 1, 2, 1, 3] [3, 1, 2]
With nulls [1, null, 2, null] [1, null, 2]

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;

import java.util.*;

import static org.junit.jupiter.api.Assertions.*;

class OrderPreservingDeduplicatorTest {

    @Test
    @DisplayName("Removes duplicates preserving order")
    void shouldDeduplicatePreservingOrder() {
        List<Integer> input = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5);
        List<Integer> result = OrderPreservingDeduplicator.deduplicate(input);
        assertEquals(Arrays.asList(3, 1, 4, 5, 9, 2, 6), result);
    }

    @Test
    @DisplayName("Null returns empty list")
    void shouldHandleNull() {
        assertTrue(OrderPreservingDeduplicator.deduplicate(null).isEmpty());
    }

    @Test
    @DisplayName("Handles null elements")
    void shouldHandleNullElements() {
        List<String> input = Arrays.asList("a", null, "b", null, "a");
        List<String> result = OrderPreservingDeduplicator.deduplicate(input);
        assertEquals(Arrays.asList("a", null, "b"), result);
    }

    @Test
    @DisplayName("Deduplicate by key works for objects")
    void shouldDeduplicateByKey() {
        record User(int id, String name) {}
        List<User> users = List.of(
                new User(1, "Alice"),
                new User(2, "Bob"),
                new User(1, "Alice2"));
        List<User> result = OrderPreservingDeduplicator.deduplicateByKey(users, User::id);
        assertEquals(2, result.size());
        assertEquals("Alice", result.get(0).name());
    }
}

Common Mistakes

  1. Using HashSet (loses order) — need LinkedHashSet or manual tracking
  2. Using contains() on a List — O(n²) total vs. O(n) with Set
  3. Modifying the input list — always return a new list
  4. Not handling null elements — LinkedHashSet supports one null

Interview Narration Tips

"LinkedHashSet is purpose-built for this: it maintains insertion order and rejects duplicates. One pass to add, then convert to list. For objects, I'd provide a deduplicateByKey variant that extracts a key field. Stream's distinct() also works but is less flexible."

Follow-up Questions

  • How would you deduplicate a stream of events in real-time?
  • What if you need to keep the last occurrence instead of the first?
  • How does distinct() work internally in Java Streams?

Q14How Would You Check for a Valid Email at a Basic Level? #

Problem Statement

Write a basic email validator without using complex regex. Validate structure: has exactly one @, non-empty local part, domain has at least one dot, no spaces. This tests practical validation for test data generation.

Optimized Solution

public class BasicEmailValidator {

    /**
     * Validates email with basic structural checks.
     * NOT a full RFC 5322 implementation — suitable for test data validation.
     *
     * @param email the email string to validate (nullable)
     * @return true if email passes basic structural validation
     */
    public static boolean isValid(String email) {
        if (email == null || email.isBlank()) {
            return false;
        }

        // No leading/trailing whitespace
        if (!email.equals(email.trim())) {
            return false;
        }

        // Exactly one @ symbol
        int atIndex = email.indexOf('@');
        if (atIndex == -1 || atIndex != email.lastIndexOf('@')) {
            return false;
        }

        String localPart = email.substring(0, atIndex);
        String domain = email.substring(atIndex + 1);

        // Local part checks
        if (localPart.isEmpty() || localPart.length() > 64) {
            return false;
        }

        // Domain checks
        if (domain.isEmpty() || domain.length() > 253) {
            return false;
        }

        // Domain must contain at least one dot
        if (!domain.contains(".")) {
            return false;
        }

        // Domain cannot start or end with dot or hyphen
        if (domain.startsWith(".") || domain.endsWith(".")
                || domain.startsWith("-") || domain.endsWith("-")) {
            return false;
        }

        // No consecutive dots in domain
        if (domain.contains("..")) {
            return false;
        }

        // TLD must be at least 2 characters
        String tld = domain.substring(domain.lastIndexOf('.') + 1);
        if (tld.length() < 2) {
            return false;
        }

        // No spaces anywhere
        if (email.contains(" ")) {
            return false;
        }

        return true;
    }

    /**
     * Regex-based validation for comparison — more concise but less readable.
     */
    public static boolean isValidRegex(String email) {
        if (email == null) return false;
        String pattern = "^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$";
        return email.matches(pattern);
    }
}

Time/Space Complexity

  • Time Complexity: O(n) — string operations are linear in email length
  • Space Complexity: O(n) — substring creation

Edge Cases

Case Input Expected
Null null false
Empty "" false
Valid basic "user@example.com" true
No @ "userexample.com" false
Multiple @ "user@@example.com" false
No domain dot "user@localhost" false
Leading space " user@example.com" false
Empty local "@example.com" false
Empty domain "user@" false
Short TLD "user@example.c" false
Consecutive dots "user@example..com" false
Valid subdomain "user@mail.example.com" true

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

import static org.junit.jupiter.api.Assertions.*;

class BasicEmailValidatorTest {

    @ParameterizedTest
    @ValueSource(strings = {
            "user@example.com",
            "first.last@domain.org",
            "user+tag@sub.domain.com",
            "a@b.co"
    })
    @DisplayName("Valid emails pass validation")
    void shouldAcceptValidEmails(String email) {
        assertTrue(BasicEmailValidator.isValid(email));
    }

    @ParameterizedTest
    @ValueSource(strings = {
            "userexample.com",
            "user@@example.com",
            "@example.com",
            "user@",
            "user@.com",
            "user@example.",
            "user @example.com",
            "user@example..com",
            "user@example.c"
    })
    @DisplayName("Invalid emails fail validation")
    void shouldRejectInvalidEmails(String email) {
        assertFalse(BasicEmailValidator.isValid(email));
    }

    @Test
    @DisplayName("Null returns false")
    void shouldRejectNull() {
        assertFalse(BasicEmailValidator.isValid(null));
    }

    @Test
    @DisplayName("Blank string returns false")
    void shouldRejectBlank() {
        assertFalse(BasicEmailValidator.isValid("   "));
    }
}

Common Mistakes

  1. Over-engineering with complex regex — hard to read, debug, and explain
  2. Not checking for exactly one @ — allows user@@domain.com
  3. Forgetting TLD length check — user@example.c shouldn't pass
  4. Claiming full RFC compliance — be honest about limitations

Interview Narration Tips

"I'd clarify: do we need full RFC 5322 compliance or practical validation? For interview purposes, I'll check structural rules step by step: one @, non-empty parts, domain has a dot, no spaces. This is readable and testable. I'd mention that production systems often use a library or send a verification email."

Follow-up Questions

  • When would you use javax.mail.internet.InternetAddress for validation?
  • How would you generate valid/invalid test emails for boundary testing?
  • What's the difference between syntactic validation and semantic validation?

Q15How Would You Parse Malformed Input Safely? #

Problem Statement

Write a method that parses a comma-separated string of integers, gracefully handling malformed entries (non-numeric, empty, whitespace, null). Return only the valid integers. This models parsing flaky test data or log files.

Optimized Solution

import java.util.*;
import java.util.stream.Collectors;

public class SafeInputParser {

    /**
     * Parses comma-separated integers, skipping malformed entries.
     *
     * @param input comma-separated string (nullable)
     * @return list of successfully parsed integers
     */
    public static List<Integer> parseIntegers(String input) {
        if (input == null || input.isBlank()) {
            return new ArrayList<>();
        }

        List<Integer> results = new ArrayList<>();
        String[] tokens = input.split(",");

        for (String token : tokens) {
            String trimmed = token.trim();
            if (trimmed.isEmpty()) continue;

            try {
                results.add(Integer.parseInt(trimmed));
            } catch (NumberFormatException e) {
                // Skip malformed entry — log in production
            }
        }

        return results;
    }

    /**
     * Parse with error reporting — returns both valid values and errors.
     */
    public static ParseResult parseWithErrors(String input) {
        if (input == null || input.isBlank()) {
            return new ParseResult(new ArrayList<>(), new ArrayList<>());
        }

        List<Integer> valid = new ArrayList<>();
        List<String> errors = new ArrayList<>();
        String[] tokens = input.split(",");

        for (int i = 0; i < tokens.length; i++) {
            String trimmed = tokens[i].trim();
            if (trimmed.isEmpty()) {
                errors.add(String.format("Position %d: empty token", i));
                continue;
            }
            try {
                valid.add(Integer.parseInt(trimmed));
            } catch (NumberFormatException e) {
                errors.add(String.format("Position %d: '%s' is not a valid integer", i, trimmed));
            }
        }

        return new ParseResult(valid, errors);
    }

    public record ParseResult(List<Integer> values, List<String> errors) {
        public boolean hasErrors() { return !errors.isEmpty(); }
    }

    /**
     * Optional-based parsing for single values.
     */
    public static Optional<Integer> tryParseInt(String value) {
        if (value == null || value.isBlank()) {
            return Optional.empty();
        }
        try {
            return Optional.of(Integer.parseInt(value.trim()));
        } catch (NumberFormatException e) {
            return Optional.empty();
        }
    }
}

Time/Space Complexity

  • Time Complexity: O(n) — where n is the length of the input string
  • Space Complexity: O(m) — where m is the number of valid integers parsed

Edge Cases

Case Input Expected
Null null []
Empty "" []
All valid "1,2,3" [1, 2, 3]
Mixed "1,abc,3" [1, 3]
Extra commas "1,,2,,,3" [1, 2, 3]
Whitespace " 1 , 2 , 3 " [1, 2, 3]
All invalid "a,b,c" []
Overflow "999999999999" [] (doesn't fit int)
Negative "-1,2,-3" [-1, 2, -3]

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;

import java.util.*;

import static org.junit.jupiter.api.Assertions.*;

class SafeInputParserTest {

    @Test
    @DisplayName("Parses valid integers correctly")
    void shouldParseValidIntegers() {
        assertEquals(List.of(1, 2, 3), SafeInputParser.parseIntegers("1,2,3"));
    }

    @Test
    @DisplayName("Skips malformed entries")
    void shouldSkipMalformed() {
        assertEquals(List.of(1, 3), SafeInputParser.parseIntegers("1,abc,3"));
    }

    @Test
    @DisplayName("Handles extra commas")
    void shouldHandleExtraCommas() {
        assertEquals(List.of(1, 2), SafeInputParser.parseIntegers("1,,2,,,"));
    }

    @Test
    @DisplayName("Trims whitespace")
    void shouldTrimWhitespace() {
        assertEquals(List.of(1, 2, 3), SafeInputParser.parseIntegers(" 1 , 2 , 3 "));
    }

    @Test
    @DisplayName("Null returns empty list")
    void shouldHandleNull() {
        assertTrue(SafeInputParser.parseIntegers(null).isEmpty());
    }

    @Test
    @DisplayName("Parse with errors reports issues")
    void shouldReportErrors() {
        var result = SafeInputParser.parseWithErrors("1,abc,3,xyz");
        assertEquals(List.of(1, 3), result.values());
        assertEquals(2, result.errors().size());
        assertTrue(result.hasErrors());
    }

    @Test
    @DisplayName("Handles negative numbers")
    void shouldHandleNegatives() {
        assertEquals(List.of(-1, 2, -3), SafeInputParser.parseIntegers("-1,2,-3"));
    }
}

Common Mistakes

  1. Not trimming tokens — " 1" fails parseInt
  2. Catching generic Exception — only catch NumberFormatException
  3. Silently swallowing errors without option to report — provide error details
  4. Using Integer.valueOf() when you don't need caching — both work, but be intentional

Interview Narration Tips

"In QA, we constantly deal with malformed data. I'd split by comma, trim each token, and use try/catch for parseInt. I'd offer two versions: one that silently skips errors (for production pipelines) and one that collects error details (for test validation). The Optional-based tryParseInt is useful as a utility."

Follow-up Questions

  • How would you parse CSV with quoted fields containing commas?
  • What's the performance impact of exception-based flow control?
  • How would you validate an entire JSON payload field by field?

Q16How Would You Test Null and Empty Cases? #

Problem Statement

Demonstrate a utility class that systematically tests null and empty inputs for any function. This shows your defensive programming mindset and understanding of boundary conditions.

Optimized Solution

import java.util.*;
import java.util.function.Function;
import java.util.function.Supplier;

public class NullSafetyTester {

    /**
     * Tests that a function handles null gracefully (doesn't throw NPE).
     *
     * @param function the function to test
     * @param <T> input type
     * @param <R> return type
     * @return true if function handles null without throwing NPE
     */
    public static <T, R> boolean handlesNull(Function<T, R> function) {
        try {
            function.apply(null);
            return true; // null handled gracefully
        } catch (NullPointerException e) {
            return false; // function is not null-safe
        } catch (Exception e) {
            return true; // other exceptions are acceptable (e.g., IllegalArgumentException)
        }
    }

    /**
     * Generates standard edge-case strings for testing.
     */
    public static List<String> edgeCaseStrings() {
        return Arrays.asList(
                null,
                "",
                " ",
                "   ",
                "\t",
                "\n",
                "\r\n",
                "null",          // literal word "null"
                "undefined",    // JavaScript artifact in APIs
                "\u0000",       // null character
                "a",            // single char
                " leading",
                "trailing ",
                " both "
        );
    }

    /**
     * Generates edge-case collections for testing.
     */
    public static <T> List<List<T>> edgeCaseLists(T sampleElement) {
        List<List<T>> cases = new ArrayList<>();
        cases.add(null);
        cases.add(Collections.emptyList());
        cases.add(Collections.singletonList(sampleElement));
        cases.add(Collections.unmodifiableList(List.of(sampleElement)));

        List<T> withNull = new ArrayList<>();
        withNull.add(null);
        cases.add(withNull);

        return cases;
    }

    /**
     * Validates that a function returns a sensible default for null/empty inputs.
     */
    public static <R> TestReport validateDefaults(
            Function<String, R> function,
            R expectedForNull,
            R expectedForEmpty) {

        List<String> failures = new ArrayList<>();

        try {
            R nullResult = function.apply(null);
            if (!Objects.equals(nullResult, expectedForNull)) {
                failures.add(String.format("null input: expected %s, got %s",
                        expectedForNull, nullResult));
            }
        } catch (Exception e) {
            failures.add("null input threw: " + e.getClass().getSimpleName());
        }

        try {
            R emptyResult = function.apply("");
            if (!Objects.equals(emptyResult, expectedForEmpty)) {
                failures.add(String.format("empty input: expected %s, got %s",
                        expectedForEmpty, emptyResult));
            }
        } catch (Exception e) {
            failures.add("empty input threw: " + e.getClass().getSimpleName());
        }

        return new TestReport(failures.isEmpty(), failures);
    }

    public record TestReport(boolean passed, List<String> failures) {}
}

Time/Space Complexity

  • Time Complexity: O(1) per test — each check is constant time
  • Space Complexity: O(k) — where k is the number of edge cases generated

Edge Cases

This question is about edge cases. Key categories:

Category Examples
Null null reference
Empty "", [], {}
Blank " ", "\t", "\n"
Boundary min/max values, single element
Special strings "null", "undefined", Unicode
Unmodifiable Collections.unmodifiableList()

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;

import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

class NullSafetyTesterTest {

    @Test
    @DisplayName("Detects null-safe function")
    void shouldDetectNullSafeFunction() {
        assertTrue(NullSafetyTester.handlesNull(s -> s == null ? "" : s.toString()));
    }

    @Test
    @DisplayName("Detects null-unsafe function")
    void shouldDetectNullUnsafeFunction() {
        assertFalse(NullSafetyTester.handlesNull((String s) -> s.length()));
    }

    @Test
    @DisplayName("Edge case strings include expected values")
    void shouldGenerateEdgeCaseStrings() {
        List<String> cases = NullSafetyTester.edgeCaseStrings();
        assertTrue(cases.contains(null));
        assertTrue(cases.contains(""));
        assertTrue(cases.contains(" "));
        assertTrue(cases.size() >= 10);
    }

    @Test
    @DisplayName("Validates default behavior for null/empty")
    void shouldValidateDefaults() {
        var report = NullSafetyTester.validateDefaults(
                s -> s == null ? 0 : s.length(),
                0,  // expected for null
                0   // expected for empty
        );
        assertTrue(report.passed());
    }

    @Test
    @DisplayName("Reports failure when defaults don't match")
    void shouldReportFailure() {
        var report = NullSafetyTester.validateDefaults(
                s -> s == null ? -1 : s.length(),
                0,  // expected 0 but function returns -1
                0
        );
        assertFalse(report.passed());
        assertEquals(1, report.failures().size());
    }
}

Common Mistakes

  1. Only testing null, not empty — empty string is a separate case from null
  2. Not testing blank (whitespace-only) — often forgotten boundary
  3. Confusing isEmpty() with isBlank() — Java 11+ distinction matters
  4. Not testing with unmodifiable collections — UnsupportedOperationException

Interview Narration Tips

"As a QA engineer, I systematically test the 'zero/null/empty' boundary for every parameter. I'd build a utility that generates standard edge cases: null, empty, blank, single element, min/max values. I'd also validate that functions return sensible defaults rather than throwing. This shows defensive programming mindset."

Follow-up Questions

  • How would you integrate null-safety testing into a CI pipeline?
  • What's your opinion on @Nullable vs. Optional for API design?
  • How would you test null handling in REST API request bodies?

Q17When Do You Use HashMap Versus HashSet? #

Problem Statement

Explain and demonstrate the practical differences between HashMap and HashSet with code examples showing when each is appropriate. This tests your understanding of Java Collections.

Optimized Solution

import java.util.*;

public class MapVsSetDemo {

    // ============ USE HASHSET WHEN ============
    // You only need to track membership (yes/no questions)

    /**
     * HashSet example: Check if any element appears in a blocklist.
     */
    public static boolean containsBlockedWord(List<String> words, Set<String> blocklist) {
        // Set.contains() is O(1) — perfect for membership testing
        for (String word : words) {
            if (blocklist.contains(word.toLowerCase())) {
                return true;
            }
        }
        return false;
    }

    /**
     * HashSet example: Find unique elements.
     */
    public static <T> int countUnique(List<T> items) {
        if (items == null) return 0;
        return new HashSet<>(items).size();
    }

    // ============ USE HASHMAP WHEN ============
    // You need to associate keys with values (lookup tables)

    /**
     * HashMap example: Count frequency of elements.
     */
    public static <T> Map<T, Integer> countFrequency(List<T> items) {
        if (items == null) return Collections.emptyMap();
        Map<T, Integer> frequency = new HashMap<>();
        for (T item : items) {
            frequency.merge(item, 1, Integer::sum);
        }
        return frequency;
    }

    /**
     * HashMap example: Index objects by a key for fast lookup.
     */
    public static <K, V> Map<K, V> indexBy(List<V> items,
                                            java.util.function.Function<V, K> keyExtractor) {
        if (items == null) return Collections.emptyMap();
        Map<K, V> index = new HashMap<>();
        for (V item : items) {
            index.put(keyExtractor.apply(item), item);
        }
        return index;
    }

    // ============ DECISION GUIDE ============

    /**
     * Quick reference for choosing:
     *
     * Question you're answering:          Use:
     * "Have I seen this before?"          HashSet
     * "How many times did I see this?"    HashMap<T, Integer>
     * "What value is associated with X?"  HashMap<K, V>
     * "What are all unique items?"        HashSet
     * "Group items by category?"          HashMap<K, List<V>>
     */
}

Time/Space Complexity

Operation HashMap HashSet
put/add O(1) avg O(1) avg
get/contains O(1) avg O(1) avg
remove O(1) avg O(1) avg
Space O(n) keys + values O(n) keys only
Worst case (hash collision) O(n) O(n)

Edge Cases

Scenario HashMap HashSet
Null key Allows ONE null key Allows ONE null element
Null value Allows null values N/A
Duplicate key Overwrites value Ignored (no change)
Thread safety Not thread-safe Not thread-safe
Ordering No guarantee No guarantee

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;

import java.util.*;

import static org.junit.jupiter.api.Assertions.*;

class MapVsSetDemoTest {

    @Test
    @DisplayName("HashSet detects blocked word")
    void shouldDetectBlockedWord() {
        Set<String> blocklist = Set.of("spam", "hack", "virus");
        List<String> words = List.of("Hello", "this", "is", "Spam");
        assertTrue(MapVsSetDemo.containsBlockedWord(words, blocklist));
    }

    @Test
    @DisplayName("HashSet counts unique elements")
    void shouldCountUnique() {
        assertEquals(3, MapVsSetDemo.countUnique(List.of(1, 2, 2, 3, 3, 3)));
    }

    @Test
    @DisplayName("HashMap counts frequency")
    void shouldCountFrequency() {
        Map<String, Integer> freq = MapVsSetDemo.countFrequency(
                List.of("a", "b", "a", "c", "b", "a"));
        assertEquals(3, freq.get("a"));
        assertEquals(2, freq.get("b"));
        assertEquals(1, freq.get("c"));
    }

    @Test
    @DisplayName("HashMap indexes by key")
    void shouldIndexByKey() {
        record User(int id, String name) {}
        List<User> users = List.of(new User(1, "Alice"), new User(2, "Bob"));
        Map<Integer, User> index = MapVsSetDemo.indexBy(users, User::id);
        assertEquals("Alice", index.get(1).name());
        assertEquals("Bob", index.get(2).name());
    }

    @Test
    @DisplayName("Null handling")
    void shouldHandleNulls() {
        assertEquals(0, MapVsSetDemo.countUnique(null));
        assertTrue(MapVsSetDemo.countFrequency(null).isEmpty());
    }
}

Common Mistakes

  1. Using HashMap when only membership is needed — wastes memory on values
  2. Using List.contains() instead of Set — O(n) vs O(1) per lookup
  3. Forgetting that HashMap allows null keys — can cause subtle bugs
  4. Not considering thread safety — use ConcurrentHashMap in multi-threaded contexts

Interview Narration Tips

"The decision is simple: if I only need to ask 'is X present?', I use HashSet. If I need to associate X with some value, I use HashMap. Internally, HashSet is actually backed by a HashMap where all values are a dummy object. I'd also mention LinkedHashMap/LinkedHashSet when order matters, and TreeMap/TreeSet when sorted order is needed."

Follow-up Questions

  • When would you choose TreeMap over HashMap?
  • How does HashMap handle hash collisions in Java 8+?
  • What's the load factor and when would you tune it?

Q18What Is the Complexity of Your Solution? #

Problem Statement

Demonstrate your ability to analyze and communicate time and space complexity. Given several code snippets, identify their Big-O complexity and explain your reasoning. This is a meta-question — interviewers want to see you can analyze any code.

Optimized Solution

import java.util.*;

public class ComplexityAnalysis {

    // ============ O(1) — CONSTANT ============
    /**
     * Array access, HashMap get, arithmetic operations.
     */
    public static int getElement(int[] arr, int index) {
        // One operation regardless of array size
        return arr[index]; // O(1)
    }

    // ============ O(log n) — LOGARITHMIC ============
    /**
     * Binary search, balanced BST operations.
     */
    public static int binarySearch(int[] sorted, int target) {
        int lo = 0, hi = sorted.length - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2; // Each iteration halves the space
            if (sorted[mid] == target) return mid;
            else if (sorted[mid] < target) lo = mid + 1;
            else hi = mid - 1;
        }
        return -1; // O(log n) — halving n times until 1
    }

    // ============ O(n) — LINEAR ============
    /**
     * Single loop, linear scan.
     */
    public static int findMax(int[] arr) {
        int max = Integer.MIN_VALUE;
        for (int val : arr) { // Visits each element once
            max = Math.max(max, val);
        }
        return max; // O(n)
    }

    // ============ O(n log n) — LINEARITHMIC ============
    /**
     * Efficient sorting (merge sort, Arrays.sort).
     */
    public static int[] sortArray(int[] arr) {
        int[] copy = arr.clone();
        Arrays.sort(copy); // O(n log n) — dual pivot quicksort
        return copy;
    }

    // ============ O(n²) — QUADRATIC ============
    /**
     * Nested loops, brute-force pair comparison.
     */
    public static List<int[]> findAllPairs(int[] arr, int targetSum) {
        List<int[]> pairs = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {         // n iterations
            for (int j = i + 1; j < arr.length; j++) { // n-1, n-2, ... iterations
                if (arr[i] + arr[j] == targetSum) {
                    pairs.add(new int[]{arr[i], arr[j]});
                }
            }
        }
        return pairs; // O(n²)
    }

    // ============ SPACE COMPLEXITY EXAMPLES ============

    /**
     * O(1) space — modifies in place or uses fixed variables.
     */
    public static void reverseInPlace(int[] arr) {
        int left = 0, right = arr.length - 1;
        while (left < right) {
            int temp = arr[left];
            arr[left++] = arr[right];
            arr[right--] = temp;
        }
        // Only 3 extra variables regardless of input size
    }

    /**
     * O(n) space — creates data structure proportional to input.
     */
    public static Set<Integer> toSet(int[] arr) {
        Set<Integer> set = new HashSet<>(); // Grows with input
        for (int val : arr) {
            set.add(val);
        }
        return set; // Space: O(n)
    }

    // ============ HOW TO ANALYZE ============

    /**
     * Framework for analyzing complexity:
     *
     * 1. Identify the input size variable (n)
     * 2. Count loops:
     *    - Single loop over n → O(n)
     *    - Nested loops over n → O(n²)
     *    - Loop that halves → O(log n)
     * 3. Check recursive calls:
     *    - T(n) = T(n/2) + O(1) → O(log n)
     *    - T(n) = 2T(n/2) + O(n) → O(n log n)
     * 4. Account for library calls:
     *    - Arrays.sort() → O(n log n)
     *    - HashMap.get() → O(1) average
     *    - String.contains() → O(n)
     * 5. Space = extra memory allocated (not counting input)
     */
}

Time/Space Complexity

Summary cheat sheet:

Complexity Name Example Acceptable For
O(1) Constant Array index, hash lookup Always ideal
O(log n) Logarithmic Binary search Large datasets
O(n) Linear Single scan Most problems
O(n log n) Linearithmic Sorting Sorting-dependent
O(n²) Quadratic Nested loops n < 10,000
O(2ⁿ) Exponential Subsets n < 20

Edge Cases

This is analytical — edge cases in complexity analysis:

  • Amortized complexity: ArrayList.add() is O(1) amortized despite occasional O(n) resize
  • Best/worst/average: QuickSort is O(n log n) average, O(n²) worst
  • Hidden operations: String concatenation in a loop is O(n²) total
  • Hash collisions: HashMap is O(1) average, O(n) worst (degenerate hash)

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Timeout;

import java.util.concurrent.TimeUnit;

import static org.junit.jupiter.api.Assertions.*;

class ComplexityAnalysisTest {

    @Test
    @DisplayName("Linear search scales linearly")
    @Timeout(value = 1, unit = TimeUnit.SECONDS)
    void linearSearchShouldCompleteInTime() {
        int[] large = new int[1_000_000];
        large[999_999] = 42;
        // If this were O(n²), it would timeout
        assertEquals(42, ComplexityAnalysis.findMax(large));
    }

    @Test
    @DisplayName("Binary search scales logarithmically")
    @Timeout(value = 100, unit = TimeUnit.MILLISECONDS)
    void binarySearchShouldBeLogarithmic() {
        int[] sorted = new int[10_000_000];
        for (int i = 0; i < sorted.length; i++) sorted[i] = i;
        // 10M elements, but only ~23 comparisons needed
        assertEquals(5_000_000, ComplexityAnalysis.binarySearch(sorted, 5_000_000));
    }

    @Test
    @DisplayName("In-place reversal uses O(1) extra space")
    void reverseInPlaceShouldModifyArray() {
        int[] arr = {1, 2, 3, 4, 5};
        ComplexityAnalysis.reverseInPlace(arr);
        assertArrayEquals(new int[]{5, 4, 3, 2, 1}, arr);
    }

    @Test
    @DisplayName("Quadratic pair finder finds all pairs")
    void shouldFindPairs() {
        int[] arr = {1, 2, 3, 4, 5};
        var pairs = ComplexityAnalysis.findAllPairs(arr, 5);
        assertEquals(2, pairs.size()); // (1,4) and (2,3)
    }
}

Common Mistakes

  1. Saying "O(n)" for everything — analyze carefully, don't guess
  2. Forgetting hidden costs — String += in a loop is O(n²)
  3. Confusing space of output with extra space — output doesn't count
  4. Not mentioning amortized analysis — ArrayList.add() is not simply O(n)

Interview Narration Tips

"When analyzing complexity, I identify the input size, count how loops scale, and check for hidden costs in library calls. I always state both time and space. If there's a tradeoff — like using a HashMap for O(1) lookup at the cost of O(n) space — I'd call that out explicitly."

Follow-up Questions

  • What's the complexity of String.substring() in Java 7 vs. Java 8+?
  • How does garbage collection affect practical performance?
  • When is O(n²) acceptable in production?

Q19How Do You Prevent Integer Overflow? #

Problem Statement

Demonstrate techniques to prevent and detect integer overflow in Java. This is critical for financial calculations, array sizing, and test data generation.

Optimized Solution

public class OverflowPrevention {

    // ============ DETECTION ============

    /**
     * Safe addition that throws on overflow.
     */
    public static int safeAdd(int a, int b) {
        return Math.addExact(a, b); // throws ArithmeticException on overflow
    }

    /**
     * Safe multiplication that throws on overflow.
     */
    public static int safeMultiply(int a, int b) {
        return Math.multiplyExact(a, b); // throws ArithmeticException on overflow
    }

    // ============ PREVENTION WITH LONG ============

    /**
     * Use long for intermediate calculations.
     */
    public static int averageWithoutOverflow(int a, int b) {
        // WRONG: (a + b) / 2 can overflow
        // RIGHT: use long for intermediate result
        return (int) (((long) a + (long) b) / 2);
    }

    /**
     * Binary search midpoint without overflow.
     */
    public static int safeMidpoint(int low, int high) {
        // WRONG: (low + high) / 2 overflows when low + high > Integer.MAX_VALUE
        // RIGHT:
        return low + (high - low) / 2;
    }

    // ============ VALIDATION BEFORE OPERATION ============

    /**
     * Check before adding to prevent overflow.
     */
    public static boolean willOverflowOnAdd(int a, int b) {
        if (b > 0 && a > Integer.MAX_VALUE - b) return true;
        if (b < 0 && a < Integer.MIN_VALUE - b) return true;
        return false;
    }

    /**
     * Safe sum of array using long accumulator.
     */
    public static long safeSum(int[] arr) {
        if (arr == null) return 0L;
        long sum = 0L; // Use long to prevent overflow
        for (int val : arr) {
            sum += val;
        }
        return sum;
    }

    // ============ BIGINTEGER FOR ARBITRARY PRECISION ============

    /**
     * For truly large numbers, use BigInteger.
     */
    public static java.math.BigInteger factorial(int n) {
        if (n < 0) throw new IllegalArgumentException("n must be non-negative");
        java.math.BigInteger result = java.math.BigInteger.ONE;
        for (int i = 2; i <= n; i++) {
            result = result.multiply(java.math.BigInteger.valueOf(i));
        }
        return result;
    }
}

Time/Space Complexity

  • Time Complexity: O(1) for overflow checks — constant time arithmetic
  • Space Complexity: O(1) — no additional data structures

Edge Cases

Case Values Risk
Max + 1 Integer.MAX_VALUE + 1 Wraps to MIN_VALUE
Min - 1 Integer.MIN_VALUE - 1 Wraps to MAX_VALUE
Max * 2 Integer.MAX_VALUE * 2 Negative result
-Min -Integer.MIN_VALUE Still MIN_VALUE!
Sum of large array [MAX_VALUE, MAX_VALUE, ...] Overflows int
Midpoint (2B + 2B) / 2 Intermediate overflow

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;

import static org.junit.jupiter.api.Assertions.*;

class OverflowPreventionTest {

    @Test
    @DisplayName("Math.addExact throws on overflow")
    void shouldThrowOnOverflow() {
        assertThrows(ArithmeticException.class,
                () -> OverflowPrevention.safeAdd(Integer.MAX_VALUE, 1));
    }

    @Test
    @DisplayName("Safe midpoint doesn't overflow")
    void shouldCalculateMidpointSafely() {
        int result = OverflowPrevention.safeMidpoint(Integer.MAX_VALUE - 2, Integer.MAX_VALUE);
        assertEquals(Integer.MAX_VALUE - 1, result);
    }

    @Test
    @DisplayName("Average of MAX values computed correctly")
    void shouldAverageWithoutOverflow() {
        int result = OverflowPrevention.averageWithoutOverflow(
                Integer.MAX_VALUE, Integer.MAX_VALUE);
        assertEquals(Integer.MAX_VALUE, result);
    }

    @Test
    @DisplayName("Overflow detection works")
    void shouldDetectPotentialOverflow() {
        assertTrue(OverflowPrevention.willOverflowOnAdd(Integer.MAX_VALUE, 1));
        assertFalse(OverflowPrevention.willOverflowOnAdd(100, 200));
    }

    @Test
    @DisplayName("Safe sum handles large arrays")
    void shouldSumSafely() {
        int[] arr = {Integer.MAX_VALUE, Integer.MAX_VALUE};
        long result = OverflowPrevention.safeSum(arr);
        assertEquals(2L * Integer.MAX_VALUE, result);
    }

    @Test
    @DisplayName("Factorial uses BigInteger for large values")
    void shouldComputeFactorial() {
        var result = OverflowPrevention.factorial(20);
        assertEquals("2432902008176640000", result.toString());
    }
}

Common Mistakes

  1. Using (a + b) / 2 for midpoint — classic binary search overflow bug
  2. Casting after overflow — (long)(a + b) is too late; cast before addition
  3. Ignoring overflow in sum loops — use long accumulator
  4. Negating Integer.MIN_VALUE — -Integer.MIN_VALUE == Integer.MIN_VALUE

Interview Narration Tips

"Java integers wrap silently on overflow — no exception by default. Three defenses: Math.addExact() for detection, long for intermediate calculations, and BigInteger for arbitrary precision. The classic interview trap is binary search midpoint: (low + high) / 2 should be low + (high - low) / 2."

Follow-up Questions

  • How do you test for overflow in financial calculations?
  • What does the JVM do differently for int vs. long operations?
  • When would you use unsigned operations in Java?

Q20How Would You Write Unit Tests for Your Function? #

Problem Statement

Given a function, demonstrate a systematic approach to writing comprehensive unit tests. Show your testing methodology: naming conventions, test structure, edge cases, parameterized tests, and assertion patterns.

Optimized Solution

import java.util.*;

/**
 * Example function to test: finds two numbers that sum to target.
 */
public class TwoSum {

    /**
     * Finds indices of two numbers that add up to target.
     *
     * @param nums   array of integers (nullable)
     * @param target the target sum
     * @return array of two indices, or empty array if no solution
     */
    public static int[] findPair(int[] nums, int target) {
        if (nums == null || nums.length < 2) {
            return new int[]{};
        }

        Map<Integer, Integer> seen = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (seen.containsKey(complement)) {
                return new int[]{seen.get(complement), i};
            }
            seen.put(nums[i], i);
        }

        return new int[]{};
    }
}
import org.junit.jupiter.api.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.*;

import java.util.stream.Stream;

import static org.junit.jupiter.api.Assertions.*;

/**
 * Comprehensive test class demonstrating senior QA testing methodology.
 *
 * Test naming convention: should_ExpectedBehavior_When_StateUnderTest
 */
@DisplayName("TwoSum.findPair()")
class TwoSumTest {

    // ============ HAPPY PATH TESTS ============

    @Nested
    @DisplayName("Happy Path")
    class HappyPath {

        @Test
        @DisplayName("Finds pair at beginning of array")
        void shouldFindPairAtBeginning() {
            int[] result = TwoSum.findPair(new int[]{2, 7, 11, 15}, 9);
            assertArrayEquals(new int[]{0, 1}, result);
        }

        @Test
        @DisplayName("Finds pair at end of array")
        void shouldFindPairAtEnd() {
            int[] result = TwoSum.findPair(new int[]{1, 2, 3, 4}, 7);
            assertArrayEquals(new int[]{2, 3}, result);
        }

        @Test
        @DisplayName("Handles negative numbers")
        void shouldHandleNegativeNumbers() {
            int[] result = TwoSum.findPair(new int[]{-1, -2, -3, -4, -5}, -8);
            assertArrayEquals(new int[]{2, 4}, result);
        }
    }

    // ============ EDGE CASE TESTS ============

    @Nested
    @DisplayName("Edge Cases")
    class EdgeCases {

        @Test
        @DisplayName("Null array returns empty")
        void shouldReturnEmptyForNull() {
            assertArrayEquals(new int[]{}, TwoSum.findPair(null, 5));
        }

        @Test
        @DisplayName("Single element returns empty")
        void shouldReturnEmptyForSingleElement() {
            assertArrayEquals(new int[]{}, TwoSum.findPair(new int[]{5}, 5));
        }

        @Test
        @DisplayName("No valid pair returns empty")
        void shouldReturnEmptyWhenNoPair() {
            assertArrayEquals(new int[]{}, TwoSum.findPair(new int[]{1, 2, 3}, 10));
        }

        @Test
        @DisplayName("Zero target with positive and negative")
        void shouldHandleZeroTarget() {
            int[] result = TwoSum.findPair(new int[]{-3, 4, 3, 90}, 0);
            assertArrayEquals(new int[]{0, 2}, result);
        }

        @Test
        @DisplayName("Duplicate values")
        void shouldHandleDuplicateValues() {
            int[] result = TwoSum.findPair(new int[]{3, 3}, 6);
            assertArrayEquals(new int[]{0, 1}, result);
        }
    }

    // ============ PARAMETERIZED TESTS ============

    @Nested
    @DisplayName("Parameterized")
    class Parameterized {

        static Stream<Arguments> validPairsProvider() {
            return Stream.of(
                    Arguments.of(new int[]{2, 7, 11, 15}, 9, new int[]{0, 1}),
                    Arguments.of(new int[]{3, 2, 4}, 6, new int[]{1, 2}),
                    Arguments.of(new int[]{3, 3}, 6, new int[]{0, 1})
            );
        }

        @ParameterizedTest
        @MethodSource("validPairsProvider")
        @DisplayName("Finds correct pair for various inputs")
        void shouldFindCorrectPair(int[] nums, int target, int[] expected) {
            assertArrayEquals(expected, TwoSum.findPair(nums, target));
        }
    }

    // ============ PROPERTY-BASED VERIFICATION ============

    @Nested
    @DisplayName("Properties")
    class Properties {

        @Test
        @DisplayName("Result indices are within bounds")
        void resultIndicesShouldBeInBounds() {
            int[] nums = {1, 5, 8, 3, 9, 2};
            int[] result = TwoSum.findPair(nums, 11);
            if (result.length == 2) {
                assertTrue(result[0] >= 0 && result[0] < nums.length);
                assertTrue(result[1] >= 0 && result[1] < nums.length);
                assertTrue(result[0] < result[1]);
            }
        }

        @Test
        @DisplayName("Result values sum to target")
        void resultValuesShouldSumToTarget() {
            int[] nums = {2, 7, 11, 15};
            int target = 9;
            int[] result = TwoSum.findPair(nums, target);
            if (result.length == 2) {
                assertEquals(target, nums[result[0]] + nums[result[1]]);
            }
        }
    }
}

Time/Space Complexity

  • Function Time: O(n) — single pass with HashMap lookups
  • Function Space: O(n) — HashMap stores up to n entries
  • Test Execution: O(n) per test case — linear in input size

Edge Cases

Testing methodology checklist:

Category What to Test
Null/Empty null input, empty array, single element
Boundaries first pair, last pair, adjacent elements
Special values zeros, negatives, MAX_VALUE
Duplicates same element twice, multiple valid pairs
No solution return value when no answer exists
Properties indices in bounds, values sum to target

Unit Tests

(The solution above IS the unit tests — this question is about testing methodology)

Common Mistakes

  1. Only testing happy path — missing null, empty, boundary cases
  2. Hard-coding expected values without reasoning — tests become brittle
  3. Not using @Nested for organization — flat test classes are hard to navigate
  4. Testing implementation details — test behavior, not internal state
  5. Not verifying properties — e.g., result indices should be valid

Interview Narration Tips

"My testing approach is systematic: start with happy path, then edge cases (null, empty, boundaries), then error cases. I use @Nested classes to organize, @ParameterizedTest to reduce duplication, and property-based assertions to verify invariants. I name tests with should_X_when_Y for readability."

Follow-up Questions

  • How do you decide which test cases to include vs. skip?
  • When would you use mocking in unit tests?
  • How do you maintain tests when requirements change?

Q21How Would You Handle Duplicate Events? #

Problem Statement

Design a mechanism to detect and handle duplicate events in an event-driven system. This is critical in QA when testing message queues, webhooks, or idempotent API calls.

Optimized Solution

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.time.Instant;
import java.time.Duration;

public class DuplicateEventHandler<T> {

    private final Map<String, Instant> processedEvents;
    private final Duration retentionWindow;

    /**
     * Creates handler with a time window for duplicate detection.
     *
     * @param retentionWindow how long to remember processed event IDs
     */
    public DuplicateEventHandler(Duration retentionWindow) {
        this.processedEvents = new ConcurrentHashMap<>();
        this.retentionWindow = retentionWindow;
    }

    /**
     * Attempts to process an event. Returns true if event is new (not duplicate).
     *
     * @param eventId unique event identifier
     * @return true if this is a new event, false if duplicate
     */
    public boolean tryProcess(String eventId) {
        if (eventId == null || eventId.isBlank()) {
            throw new IllegalArgumentException("Event ID must not be null or blank");
        }

        Instant now = Instant.now();
        Instant previous = processedEvents.putIfAbsent(eventId, now);

        return previous == null; // null means it was new
    }

    /**
     * Checks if an event has already been processed.
     */
    public boolean isDuplicate(String eventId) {
        if (eventId == null) return false;
        Instant processed = processedEvents.get(eventId);
        if (processed == null) return false;

        // Check if within retention window
        if (Duration.between(processed, Instant.now()).compareTo(retentionWindow) > 0) {
            processedEvents.remove(eventId);
            return false; // expired, treat as new
        }
        return true;
    }

    /**
     * Cleans up expired entries to prevent memory growth.
     */
    public int cleanup() {
        Instant cutoff = Instant.now().minus(retentionWindow);
        int removed = 0;
        Iterator<Map.Entry<String, Instant>> iter = processedEvents.entrySet().iterator();
        while (iter.hasNext()) {
            if (iter.next().getValue().isBefore(cutoff)) {
                iter.remove();
                removed++;
            }
        }
        return removed;
    }

    /**
     * Returns count of tracked events.
     */
    public int trackedCount() {
        return processedEvents.size();
    }
}

Time/Space Complexity

  • Time Complexity: O(1) per event — ConcurrentHashMap operations are constant time
  • Space Complexity: O(n) — where n is the number of unique events in the retention window

Edge Cases

Case Scenario Expected Behavior
First event New event ID tryProcess returns true
Duplicate Same ID sent twice Second call returns false
Expired event Event older than retention Treated as new
Null ID null event ID IllegalArgumentException
Blank ID "" event ID IllegalArgumentException
Concurrent Two threads, same event Only one returns true
Memory Millions of events Cleanup removes expired

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.BeforeEach;

import java.time.Duration;

import static org.junit.jupiter.api.Assertions.*;

class DuplicateEventHandlerTest {

    private DuplicateEventHandler<String> handler;

    @BeforeEach
    void setUp() {
        handler = new DuplicateEventHandler<>(Duration.ofMinutes(5));
    }

    @Test
    @DisplayName("First event is processed successfully")
    void shouldProcessNewEvent() {
        assertTrue(handler.tryProcess("event-001"));
    }

    @Test
    @DisplayName("Duplicate event is rejected")
    void shouldRejectDuplicate() {
        handler.tryProcess("event-001");
        assertFalse(handler.tryProcess("event-001"));
    }

    @Test
    @DisplayName("Different events are both processed")
    void shouldProcessDifferentEvents() {
        assertTrue(handler.tryProcess("event-001"));
        assertTrue(handler.tryProcess("event-002"));
    }

    @Test
    @DisplayName("Null event ID throws exception")
    void shouldThrowForNullId() {
        assertThrows(IllegalArgumentException.class,
                () -> handler.tryProcess(null));
    }

    @Test
    @DisplayName("Blank event ID throws exception")
    void shouldThrowForBlankId() {
        assertThrows(IllegalArgumentException.class,
                () -> handler.tryProcess("  "));
    }

    @Test
    @DisplayName("Duplicate detection works")
    void shouldDetectDuplicate() {
        handler.tryProcess("event-001");
        assertTrue(handler.isDuplicate("event-001"));
        assertFalse(handler.isDuplicate("event-999"));
    }

    @Test
    @DisplayName("Tracked count increases")
    void shouldTrackCount() {
        handler.tryProcess("event-001");
        handler.tryProcess("event-002");
        handler.tryProcess("event-001"); // duplicate
        assertEquals(2, handler.trackedCount());
    }
}

Common Mistakes

  1. Using an unbounded Set — memory leak without cleanup/TTL
  2. Not using thread-safe collections — events often arrive concurrently
  3. Checking and inserting separately — race condition without putIfAbsent
  4. Not considering the retention window — should old events be re-processable?

Interview Narration Tips

"Duplicate events are common in distributed systems — at-least-once delivery guarantees mean duplicates will happen. I'd use a ConcurrentHashMap with putIfAbsent for atomic check-and-insert. Key design decisions: retention window (can't store forever), thread safety, and cleanup strategy. In QA, I'd test race conditions with concurrent submissions."

Follow-up Questions

  • How would you scale this across multiple service instances (Redis, database)?
  • What's the difference between idempotent processing and duplicate detection?
  • How would you test the thread-safety of this handler?

Q22How Would You Implement Retry with a Cap? #

Problem Statement

Implement a retry mechanism with exponential backoff and a maximum attempt cap. This is essential for testing flaky services, network calls, and asynchronous operations.

Optimized Solution

import java.time.Duration;
import java.util.function.Supplier;
import java.util.concurrent.Callable;

public class RetryHandler {

    private final int maxAttempts;
    private final Duration initialDelay;
    private final double backoffMultiplier;
    private final Duration maxDelay;

    private RetryHandler(Builder builder) {
        this.maxAttempts = builder.maxAttempts;
        this.initialDelay = builder.initialDelay;
        this.backoffMultiplier = builder.backoffMultiplier;
        this.maxDelay = builder.maxDelay;
    }

    /**
     * Executes an operation with retry logic.
     *
     * @param operation the operation to retry
     * @param <T> return type
     * @return result of successful operation
     * @throws RetryExhaustedException if all attempts fail
     */
    public <T> T execute(Callable<T> operation) throws RetryExhaustedException {
        Exception lastException = null;
        long currentDelayMs = initialDelay.toMillis();

        for (int attempt = 1; attempt <= maxAttempts; attempt++) {
            try {
                return operation.call();
            } catch (Exception e) {
                lastException = e;

                if (attempt == maxAttempts) {
                    break; // Don't sleep after final attempt
                }

                sleep(currentDelayMs);
                currentDelayMs = Math.min(
                        (long) (currentDelayMs * backoffMultiplier),
                        maxDelay.toMillis()
                );
            }
        }

        throw new RetryExhaustedException(
                String.format("Failed after %d attempts", maxAttempts),
                lastException
        );
    }

    /**
     * Executes a void operation with retry logic.
     */
    public void executeVoid(Runnable operation) throws RetryExhaustedException {
        execute(() -> { operation.run(); return null; });
    }

    private void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("Retry interrupted", e);
        }
    }

    // ============ BUILDER ============

    public static Builder builder() {
        return new Builder();
    }

    public static class Builder {
        private int maxAttempts = 3;
        private Duration initialDelay = Duration.ofMillis(100);
        private double backoffMultiplier = 2.0;
        private Duration maxDelay = Duration.ofSeconds(30);

        public Builder maxAttempts(int maxAttempts) {
            if (maxAttempts < 1) throw new IllegalArgumentException("maxAttempts must be >= 1");
            this.maxAttempts = maxAttempts;
            return this;
        }

        public Builder initialDelay(Duration initialDelay) {
            this.initialDelay = initialDelay;
            return this;
        }

        public Builder backoffMultiplier(double multiplier) {
            if (multiplier < 1.0) throw new IllegalArgumentException("multiplier must be >= 1.0");
            this.backoffMultiplier = multiplier;
            return this;
        }

        public Builder maxDelay(Duration maxDelay) {
            this.maxDelay = maxDelay;
            return this;
        }

        public RetryHandler build() {
            return new RetryHandler(this);
        }
    }

    // ============ EXCEPTION ============

    public static class RetryExhaustedException extends Exception {
        public RetryExhaustedException(String message, Throwable cause) {
            super(message, cause);
        }
    }
}

Time/Space Complexity

  • Time Complexity: O(maxAttempts) — bounded by configuration
  • Space Complexity: O(1) — only stores delay and attempt counter
  • Wall time: Sum of delays = initialDelay × (multiplier^0 + multiplier^1 + ... + multiplier^(n-1))

Edge Cases

Case Scenario Expected
First attempt succeeds No failures Return immediately, no delay
All attempts fail Persistent failure Throw RetryExhaustedException
Succeeds on last try n-1 failures then success Return result
Thread interrupted Sleep interrupted Rethrow with interrupt flag
Max delay cap Backoff exceeds max Delay capped at maxDelay
maxAttempts = 1 No retry Fail immediately or succeed

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;

import java.time.Duration;
import java.util.concurrent.atomic.AtomicInteger;

import static org.junit.jupiter.api.Assertions.*;

class RetryHandlerTest {

    @Test
    @DisplayName("Succeeds on first attempt without delay")
    void shouldSucceedImmediately() throws Exception {
        RetryHandler handler = RetryHandler.builder()
                .maxAttempts(3)
                .initialDelay(Duration.ofMillis(10))
                .build();

        String result = handler.execute(() -> "success");
        assertEquals("success", result);
    }

    @Test
    @DisplayName("Retries and succeeds on third attempt")
    void shouldRetryAndSucceed() throws Exception {
        AtomicInteger attempts = new AtomicInteger(0);
        RetryHandler handler = RetryHandler.builder()
                .maxAttempts(3)
                .initialDelay(Duration.ofMillis(10))
                .build();

        String result = handler.execute(() -> {
            if (attempts.incrementAndGet() < 3) {
                throw new RuntimeException("Not yet");
            }
            return "finally";
        });

        assertEquals("finally", result);
        assertEquals(3, attempts.get());
    }

    @Test
    @DisplayName("Throws after exhausting all attempts")
    void shouldThrowAfterMaxAttempts() {
        RetryHandler handler = RetryHandler.builder()
                .maxAttempts(3)
                .initialDelay(Duration.ofMillis(10))
                .build();

        assertThrows(RetryHandler.RetryExhaustedException.class,
                () -> handler.execute(() -> { throw new RuntimeException("fail"); }));
    }

    @Test
    @DisplayName("Builder validates maxAttempts")
    void shouldRejectInvalidMaxAttempts() {
        assertThrows(IllegalArgumentException.class,
                () -> RetryHandler.builder().maxAttempts(0));
    }

    @Test
    @DisplayName("Builder validates backoff multiplier")
    void shouldRejectInvalidMultiplier() {
        assertThrows(IllegalArgumentException.class,
                () -> RetryHandler.builder().backoffMultiplier(0.5));
    }

    @Test
    @DisplayName("Respects max delay cap")
    void shouldCapDelay() throws Exception {
        AtomicInteger attempts = new AtomicInteger(0);
        long start = System.currentTimeMillis();

        RetryHandler handler = RetryHandler.builder()
                .maxAttempts(5)
                .initialDelay(Duration.ofMillis(10))
                .backoffMultiplier(100.0) // aggressive backoff
                .maxDelay(Duration.ofMillis(50)) // but capped
                .build();

        assertThrows(RetryHandler.RetryExhaustedException.class,
                () -> handler.execute(() -> { throw new RuntimeException("fail"); }));

        long elapsed = System.currentTimeMillis() - start;
        assertTrue(elapsed < 1000, "Should complete quickly due to max delay cap");
    }
}

Common Mistakes

  1. No maximum attempts — infinite retry loop
  2. No backoff — hammering a failing service makes things worse
  3. Not capping the delay — exponential growth leads to absurd waits
  4. Sleeping after the last attempt — wasted time
  5. Not preserving InterruptedException — breaks thread pool shutdown

Interview Narration Tips

"I'd use exponential backoff with three safeguards: max attempts, max delay cap, and backoff multiplier. Builder pattern makes it configurable. Key design choices: use Callable<T> for type-safe returns, cap delay to prevent absurd waits, and preserve the last exception for debugging. In QA, this is essential for testing flaky services."

Follow-up Questions

  • How would you add jitter to prevent thundering herd?
  • How would you make certain exceptions non-retriable?
  • How would you test retry behavior without actual sleep delays?

Q23How Would You Sort Objects by Multiple Fields? #

Problem Statement

Sort a list of objects by multiple fields with different priorities and directions (ascending/descending). This is common when sorting test results, logs, or report data.

Optimized Solution

import java.util.*;
import java.util.stream.Collectors;

public class MultiFieldSorter {

    /**
     * Example domain object: a test result.
     */
    public record TestResult(
            String suiteName,
            String status,     // PASSED, FAILED, ERROR
            long durationMs,
            String testName
    ) {}

    /**
     * Sort test results by: status (FAILED first), then duration (desc), then name.
     */
    public static List<TestResult> sortTestResults(List<TestResult> results) {
        if (results == null || results.isEmpty()) {
            return new ArrayList<>();
        }

        // Define status priority
        Map<String, Integer> statusPriority = Map.of(
                "FAILED", 0,
                "ERROR", 1,
                "PASSED", 2
        );

        Comparator<TestResult> comparator = Comparator
                .comparingInt((TestResult r) ->
                        statusPriority.getOrDefault(r.status(), 99))
                .thenComparing(
                        Comparator.comparingLong(TestResult::durationMs).reversed())
                .thenComparing(TestResult::testName, String.CASE_INSENSITIVE_ORDER);

        return results.stream()
                .sorted(comparator)
                .collect(Collectors.toList());
    }

    /**
     * Generic multi-field sort with configurable comparators.
     */
    @SafeVarargs
    public static <T> List<T> sortByFields(List<T> items, Comparator<T>... comparators) {
        if (items == null || items.isEmpty()) {
            return new ArrayList<>();
        }
        if (comparators.length == 0) {
            return new ArrayList<>(items);
        }

        Comparator<T> combined = comparators[0];
        for (int i = 1; i < comparators.length; i++) {
            combined = combined.thenComparing(comparators[i]);
        }

        return items.stream()
                .sorted(combined)
                .collect(Collectors.toList());
    }

    /**
     * Sort with null-safe comparators.
     */
    public static <T> Comparator<T> nullSafeComparator(
            Comparator<T> comparator, boolean nullsFirst) {
        if (nullsFirst) {
            return Comparator.nullsFirst(comparator);
        }
        return Comparator.nullsLast(comparator);
    }
}

Time/Space Complexity

  • Time Complexity: O(n log n) — dominated by the sort algorithm (TimSort)
  • Space Complexity: O(n) — creating a new sorted list

Edge Cases

Case Input Expected
Null list null []
Empty list [] []
Single element one item same item
All equal primary same status sorted by secondary
Null fields null testName doesn't crash
Unknown status status not in priority map sorts last (99)
Same everything identical objects stable order

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;

import java.util.*;

import static org.junit.jupiter.api.Assertions.*;

class MultiFieldSorterTest {

    @Test
    @DisplayName("Sorts by status priority first")
    void shouldSortByStatusFirst() {
        List<MultiFieldSorter.TestResult> results = List.of(
                new MultiFieldSorter.TestResult("Suite1", "PASSED", 100, "test1"),
                new MultiFieldSorter.TestResult("Suite1", "FAILED", 50, "test2"),
                new MultiFieldSorter.TestResult("Suite1", "ERROR", 200, "test3")
        );

        List<MultiFieldSorter.TestResult> sorted = MultiFieldSorter.sortTestResults(results);
        assertEquals("FAILED", sorted.get(0).status());
        assertEquals("ERROR", sorted.get(1).status());
        assertEquals("PASSED", sorted.get(2).status());
    }

    @Test
    @DisplayName("Sorts by duration descending within same status")
    void shouldSortByDurationDescending() {
        List<MultiFieldSorter.TestResult> results = List.of(
                new MultiFieldSorter.TestResult("Suite1", "FAILED", 100, "test1"),
                new MultiFieldSorter.TestResult("Suite1", "FAILED", 500, "test2"),
                new MultiFieldSorter.TestResult("Suite1", "FAILED", 200, "test3")
        );

        List<MultiFieldSorter.TestResult> sorted = MultiFieldSorter.sortTestResults(results);
        assertEquals(500, sorted.get(0).durationMs());
        assertEquals(200, sorted.get(1).durationMs());
        assertEquals(100, sorted.get(2).durationMs());
    }

    @Test
    @DisplayName("Sorts by name as tiebreaker")
    void shouldSortByNameAsTiebreaker() {
        List<MultiFieldSorter.TestResult> results = List.of(
                new MultiFieldSorter.TestResult("S", "PASSED", 100, "Zebra"),
                new MultiFieldSorter.TestResult("S", "PASSED", 100, "Alpha")
        );

        List<MultiFieldSorter.TestResult> sorted = MultiFieldSorter.sortTestResults(results);
        assertEquals("Alpha", sorted.get(0).testName());
    }

    @Test
    @DisplayName("Null list returns empty")
    void shouldHandleNull() {
        assertTrue(MultiFieldSorter.sortTestResults(null).isEmpty());
    }

    @Test
    @DisplayName("Generic multi-field sort works")
    void shouldSortGenericByFields() {
        List<String> items = List.of("banana", "Apple", "cherry", "apple");

        List<String> sorted = MultiFieldSorter.sortByFields(items,
                Comparator.comparingInt(String::length),
                String.CASE_INSENSITIVE_ORDER);

        assertEquals("Apple", sorted.get(0)); // length 5, alphabetically first
    }
}

Common Mistakes

  1. Writing manual comparison logic — use Comparator.comparing().thenComparing()
  2. Forgetting .reversed() for descending — natural order is ascending
  3. Not handling nulls in fields — NPE during comparison
  4. Mutating the input list — use stream().sorted() to return a new list
  5. Case-sensitive name comparison — use String.CASE_INSENSITIVE_ORDER

Interview Narration Tips

"Java's Comparator API is powerful for multi-field sorting. I chain comparators with thenComparing(), use reversed() for descending, and Comparator.nullsFirst/Last for null safety. I'd define status priority in a Map for readability. TimSort gives stable sort, so equal elements maintain their relative order."

Follow-up Questions

  • How would you implement a dynamic sort based on user-selected columns?
  • What's the difference between Comparable and Comparator?
  • How does TimSort's stability help with multi-field sorting?

Q24How Would You Find the Top K Frequent Values? #

Problem Statement

Given a list of elements, find the K most frequently occurring values. This models finding the most common test failures, most frequent error codes, or top API endpoints by call volume.

Optimized Solution

import java.util.*;
import java.util.stream.Collectors;

public class TopKFrequent {

    /**
     * Finds the top K most frequent elements using a min-heap.
     *
     * @param items list of elements (nullable)
     * @param k     number of top elements to return
     * @return list of K most frequent elements, ordered by frequency (desc)
     */
    public static <T> List<T> findTopK(List<T> items, int k) {
        if (items == null || items.isEmpty() || k <= 0) {
            return new ArrayList<>();
        }

        // Step 1: Count frequencies
        Map<T, Integer> frequency = new HashMap<>();
        for (T item : items) {
            if (item != null) {
                frequency.merge(item, 1, Integer::sum);
            }
        }

        // Step 2: Use min-heap of size K
        PriorityQueue<Map.Entry<T, Integer>> minHeap = new PriorityQueue<>(
                Comparator.comparingInt(Map.Entry::getValue)
        );

        for (Map.Entry<T, Integer> entry : frequency.entrySet()) {
            minHeap.offer(entry);
            if (minHeap.size() > k) {
                minHeap.poll(); // Remove least frequent
            }
        }

        // Step 3: Extract results (most frequent first)
        List<T> result = new ArrayList<>();
        while (!minHeap.isEmpty()) {
            result.add(minHeap.poll().getKey());
        }
        Collections.reverse(result);
        return result;
    }

    /**
     * Bucket sort approach — O(n) time when K is close to n.
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> findTopKBucketSort(List<T> items, int k) {
        if (items == null || items.isEmpty() || k <= 0) {
            return new ArrayList<>();
        }

        // Count frequencies
        Map<T, Integer> frequency = new HashMap<>();
        for (T item : items) {
            if (item != null) {
                frequency.merge(item, 1, Integer::sum);
            }
        }

        // Create buckets where index = frequency
        List<T>[] buckets = new List[items.size() + 1];
        for (Map.Entry<T, Integer> entry : frequency.entrySet()) {
            int freq = entry.getValue();
            if (buckets[freq] == null) {
                buckets[freq] = new ArrayList<>();
            }
            buckets[freq].add(entry.getKey());
        }

        // Collect from highest frequency bucket down
        List<T> result = new ArrayList<>();
        for (int i = buckets.length - 1; i >= 0 && result.size() < k; i--) {
            if (buckets[i] != null) {
                result.addAll(buckets[i]);
            }
        }

        return result.subList(0, Math.min(k, result.size()));
    }

    /**
     * Stream-based approach — concise but less efficient for large K.
     */
    public static <T> List<T> findTopKStream(List<T> items, int k) {
        if (items == null || items.isEmpty() || k <= 0) {
            return new ArrayList<>();
        }

        return items.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.groupingBy(i -> i, Collectors.counting()))
                .entrySet().stream()
                .sorted(Map.Entry.<T, Long>comparingByValue().reversed())
                .limit(k)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
    }
}

Time/Space Complexity

Approach Time Space Best When
Min-Heap O(n log k) O(n + k) k << n
Bucket Sort O(n) O(n) k close to n
Stream Sort O(n log n) O(n) Readability priority

Edge Cases

Case Input Expected
Null null, 3 []
Empty [], 3 []
k = 0 [1,1,2], 0 []
k > unique count [1,1,2], 5 [1, 2]
All same [1,1,1], 1 [1]
Tie in frequency [1,1,2,2], 1 either [1] or [2]
Null elements [1,null,1], 1 [1]

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;

import java.util.*;

import static org.junit.jupiter.api.Assertions.*;

class TopKFrequentTest {

    @Test
    @DisplayName("Finds top K frequent elements")
    void shouldFindTopK() {
        List<Integer> items = List.of(1, 1, 1, 2, 2, 3);
        List<Integer> result = TopKFrequent.findTopK(items, 2);
        assertEquals(2, result.size());
        assertEquals(1, result.get(0)); // most frequent
        assertTrue(result.contains(2)); // second most
    }

    @Test
    @DisplayName("K larger than unique elements returns all")
    void shouldHandleKLargerThanUnique() {
        List<String> items = List.of("a", "b", "a");
        List<String> result = TopKFrequent.findTopK(items, 10);
        assertEquals(2, result.size());
    }

    @Test
    @DisplayName("Null returns empty list")
    void shouldHandleNull() {
        assertTrue(TopKFrequent.findTopK(null, 3).isEmpty());
    }

    @Test
    @DisplayName("K = 0 returns empty")
    void shouldHandleKZero() {
        assertTrue(TopKFrequent.findTopK(List.of(1, 2, 3), 0).isEmpty());
    }

    @Test
    @DisplayName("Handles null elements in list")
    void shouldIgnoreNullElements() {
        List<Integer> items = Arrays.asList(1, null, 1, null, 2);
        List<Integer> result = TopKFrequent.findTopK(items, 1);
        assertEquals(List.of(1), result);
    }

    @Test
    @DisplayName("Bucket sort produces same results")
    void bucketSortShouldMatchHeap() {
        List<Integer> items = List.of(1, 1, 1, 2, 2, 3, 3, 3, 3);
        List<Integer> heapResult = TopKFrequent.findTopK(items, 2);
        List<Integer> bucketResult = TopKFrequent.findTopKBucketSort(items, 2);

        assertEquals(new HashSet<>(heapResult), new HashSet<>(bucketResult));
    }

    @Test
    @DisplayName("Works with strings — top error messages")
    void shouldWorkWithStrings() {
        List<String> errors = List.of(
                "timeout", "timeout", "timeout",
                "404", "404",
                "500",
                "connection_refused", "connection_refused", "connection_refused", "connection_refused"
        );
        List<String> top2 = TopKFrequent.findTopK(errors, 2);
        assertTrue(top2.contains("connection_refused"));
        assertTrue(top2.contains("timeout"));
    }
}

Common Mistakes

  1. Sorting the entire frequency map — O(n log n) when O(n log k) is possible
  2. Using a max-heap of size n — min-heap of size K is more efficient
  3. Not handling ties — clarify with interviewer what to do
  4. Forgetting null elements in the input — filter them out
  5. Off-by-one with k — returning k+1 or k-1 elements

Interview Narration Tips

"Three approaches: min-heap for optimal O(n log k), bucket sort for O(n) when frequency range is bounded, and streams for readability. I'd choose min-heap as default: count frequencies in a HashMap, then maintain a min-heap of size K. When the heap exceeds K, poll the minimum — what remains are the top K. In QA, this finds top failure reasons in test suites."

Follow-up Questions

  • How would you handle real-time streaming data (top K in a sliding window)?
  • What if K is very close to n — which approach wins?
  • How would you break ties (e.g., alphabetical order)?

Q25How Do You Review Your Code Before Submitting? #

Problem Statement

Describe and demonstrate a systematic code review checklist that you apply to your own code before submitting in an interview or PR. Show code examples of common issues caught during self-review.

Optimized Solution

import java.util.*;

/**
 * Demonstration: A function BEFORE self-review (with issues)
 * vs. AFTER self-review (corrected).
 */
public class CodeReviewChecklist {

    // ============ BEFORE REVIEW (common issues) ============

    /**
     * PROBLEMATIC VERSION — multiple issues to catch in review.
     */
    public static List<String> processDataBad(List<String> data) {
        // Issue 1: No null check
        // Issue 2: Modifies input list
        // Issue 3: No meaningful variable names
        // Issue 4: Swallows exception silently
        // Issue 5: Uses raw types
        ArrayList result = new ArrayList();
        for (int i = 0; i < data.size(); i++) {
            try {
                String s = data.get(i);
                if (s.length() > 0) { // Issue 6: should use isEmpty()
                    result.add(s.toUpperCase());
                }
            } catch (Exception e) {
                // silent catch
            }
        }
        return result;
    }

    // ============ AFTER REVIEW (corrected) ============

    /**
     * REVIEWED VERSION — all issues addressed.
     */
    public static List<String> processData(List<String> data) {
        if (data == null || data.isEmpty()) {
            return new ArrayList<>(); // Issue 1: null/empty handled
        }

        List<String> uppercased = new ArrayList<>(data.size()); // Sized appropriately

        for (String item : data) { // Enhanced for-loop, no index needed
            if (item != null && !item.isEmpty()) { // Null-safe, uses isEmpty()
                uppercased.add(item.toUpperCase());
            }
            // Null/empty items are skipped — documented behavior
        }

        return Collections.unmodifiableList(uppercased); // Immutable return
    }

    // ============ THE CHECKLIST ============

    /**
     * Self-review checklist — apply before submitting:
     *
     * 1. CORRECTNESS
     *    □ Does it handle null inputs?
     *    □ Does it handle empty inputs?
     *    □ Does it handle single-element inputs?
     *    □ Are boundary conditions correct (off-by-one)?
     *    □ Does it return the right type (mutable vs. immutable)?
     *
     * 2. EDGE CASES
     *    □ What if the collection has null elements?
     *    □ What about Integer.MAX_VALUE / MIN_VALUE?
     *    □ What about empty strings vs. null strings?
     *    □ What about concurrent modification?
     *
     * 3. CODE QUALITY
     *    □ Are variable names descriptive?
     *    □ Are there unnecessary comments (code should be self-documenting)?
     *    □ Is there dead code?
     *    □ Are generics used properly (no raw types)?
     *    □ Is the method too long (> 20 lines)?
     *
     * 4. PERFORMANCE
     *    □ Is time complexity optimal for the problem?
     *    □ Are there unnecessary object allocations in loops?
     *    □ Is String concatenation in a loop? (Use StringBuilder)
     *    □ Are collections pre-sized when possible?
     *
     * 5. SAFETY
     *    □ Can this throw NPE? Where?
     *    □ Can this overflow? (int arithmetic)
     *    □ Are exceptions handled appropriately (not swallowed)?
     *    □ Is the input modified (side effects)?
     *
     * 6. TESTABILITY
     *    □ Can this be unit tested in isolation?
     *    □ Are dependencies injectable?
     *    □ Is the output deterministic?
     */

    // ============ COMMON ANTI-PATTERNS TO CATCH ============

    /**
     * Anti-pattern 1: String concatenation in loop.
     */
    public static String joinBad(List<String> items) {
        String result = "";
        for (String item : items) {
            result += item + ","; // O(n²) — creates new String each iteration
        }
        return result;
    }

    /** Fixed: Use StringBuilder or String.join() */
    public static String joinGood(List<String> items) {
        if (items == null || items.isEmpty()) return "";
        return String.join(",", items); // O(n)
    }

    /**
     * Anti-pattern 2: Checking contains then get on map.
     */
    public static String lookupBad(Map<String, String> map, String key) {
        if (map.containsKey(key)) { // First hash lookup
            return map.get(key);     // Second hash lookup (redundant)
        }
        return "default";
    }

    /** Fixed: Use getOrDefault */
    public static String lookupGood(Map<String, String> map, String key) {
        return map.getOrDefault(key, "default"); // Single lookup
    }

    /**
     * Anti-pattern 3: Catching broad exceptions.
     */
    public static int parseBad(String value) {
        try {
            return Integer.parseInt(value);
        } catch (Exception e) { // Too broad — hides bugs
            return 0;
        }
    }

    /** Fixed: Catch specific exception */
    public static OptionalInt parseGood(String value) {
        if (value == null || value.isBlank()) {
            return OptionalInt.empty();
        }
        try {
            return OptionalInt.of(Integer.parseInt(value.trim()));
        } catch (NumberFormatException e) {
            return OptionalInt.empty(); // Specific exception, Optional return
        }
    }
}

Time/Space Complexity

  • Review process: O(n) — scan each line once with checklist in mind
  • The review itself doesn't add complexity to the code — it prevents costly bugs

Edge Cases

Self-review catches these categories:

Category Example Issue Fix
Null safety NPE on data.size() Add null check
Mutability Returning internal list Return unmodifiable copy
Resource leaks Unclosed streams/connections try-with-resources
Thread safety Shared mutable state Use concurrent structures
API misuse equals() on arrays Use Arrays.equals()

Unit Tests

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;

import java.util.*;

import static org.junit.jupiter.api.Assertions.*;

class CodeReviewChecklistTest {

    @Test
    @DisplayName("processData handles null input")
    void shouldHandleNullInput() {
        List<String> result = CodeReviewChecklist.processData(null);
        assertNotNull(result);
        assertTrue(result.isEmpty());
    }

    @Test
    @DisplayName("processData handles null elements")
    void shouldHandleNullElements() {
        List<String> input = Arrays.asList("hello", null, "world");
        List<String> result = CodeReviewChecklist.processData(input);
        assertEquals(List.of("HELLO", "WORLD"), result);
    }

    @Test
    @DisplayName("processData returns immutable list")
    void shouldReturnImmutableList() {
        List<String> result = CodeReviewChecklist.processData(List.of("test"));
        assertThrows(UnsupportedOperationException.class, () -> result.add("new"));
    }

    @Test
    @DisplayName("joinGood is O(n) efficient")
    void shouldJoinEfficiently() {
        List<String> items = List.of("a", "b", "c");
        assertEquals("a,b,c", CodeReviewChecklist.joinGood(items));
    }

    @Test
    @DisplayName("parseGood returns empty for invalid input")
    void shouldReturnEmptyForInvalid() {
        assertTrue(CodeReviewChecklist.parseGood(null).isEmpty());
        assertTrue(CodeReviewChecklist.parseGood("abc").isEmpty());
        assertEquals(42, CodeReviewChecklist.parseGood("42").orElse(-1));
    }

    @Test
    @DisplayName("lookupGood uses single hash lookup")
    void shouldLookupWithDefault() {
        Map<String, String> map = Map.of("key", "value");
        assertEquals("value", CodeReviewChecklist.lookupGood(map, "key"));
        assertEquals("default", CodeReviewChecklist.lookupGood(map, "missing"));
    }
}

Common Mistakes

  1. Not reviewing at all — submitting first draft without a second look
  2. Only checking if it compiles — compilation ≠ correctness
  3. Not tracing through with sample input — dry-run catches logic errors
  4. Ignoring the "what if null" question — most NPEs are preventable
  5. Not reading the problem statement again — solving the wrong problem

Interview Narration Tips

"Before submitting, I walk through a mental checklist: null/empty handling, edge cases, naming, complexity, and potential exceptions. I trace through my code with at least one happy path and one edge case. I check for common anti-patterns: string concat in loops, raw types, broad catch blocks. This 60-second review catches 80% of bugs."

Follow-up Questions

  • How do you prioritize what to review when time is limited?
  • How does self-review differ from reviewing someone else's code?
  • What static analysis tools would you use in a CI pipeline?

Chapter Summary #

Key Takeaways

  1. Always handle null/empty — this is the #1 differentiator between mid and senior candidates
  2. Know your complexity — state time and space for every solution
  3. Use the right data structure — HashMap for lookup, HashSet for membership, PriorityQueue for top-K
  4. Communicate your approach — narrate before coding
  5. Test systematically — happy path → edge cases → error cases → properties

Quick Reference: When to Use What

Problem Pattern Data Structure Time
Frequency counting HashMap O(n)
Duplicate detection HashSet O(n)
Matching brackets Stack (ArrayDeque) O(n)
Sorted search Binary search O(log n)
Top K elements Min-heap (PriorityQueue) O(n log k)
Order-preserving dedup LinkedHashSet O(n)
Multi-field sort Comparator chain O(n log n)
Interval problems Sort + sweep O(n log n)

Interview Day Checklist

  • Clarify requirements before coding
  • State your approach and complexity before writing
  • Handle null and empty first
  • Use meaningful variable names
  • Test with at least one example mentally
  • Review your code using the checklist from Question 25
  • Ask "What would I test?" — then mention those cases

Finished this chapter?

Mark it as done to track your progress on the guide overview. Progress is kept only while this browser tab is open.

← Back to chapters