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
Read the problem statement — pause and think before reading the solution
Write your own solution — then compare with the optimized version
Study the edge cases — these are what separate senior from mid-level candidates
Practice narration — say your thought process out loud
Run the unit tests — modify them to add your own scenarios
Write a method that reverses a string, handling null input, empty strings, Unicode surrogate pairs, and whitespace-only strings without throwing exceptions.
Optimized Solution
publicclassStringReverser {
/**
* 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
*/publicstaticStringreverse(String input) {
if (input == null) {
returnnull;
}
if (input.length() <= 1) {
return input;
}
// StringBuilder.reverse() handles surrogate pairs correctlyreturnnewStringBuilder(input).reverse().toString();
}
/**
* Reverses a string manually — useful to demonstrate algorithm knowledge.
*/publicstaticStringreverseManual(String input) {
if (input == null) {
returnnull;
}
char[] chars= input.toCharArray();
intleft=0;
intright= chars.length - 1;
while (left < right) {
// Handle surrogate pairsif (Character.isHighSurrogate(chars[left]) && left + 1 < right) {
// Swap the pair as a unitcharhighLeft= chars[left];
charlowLeft= 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 {
chartemp= chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
}
returnnewString(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
Not handling null — throws NullPointerException immediately
Using char array swap without surrogate pair awareness — corrupts emoji/CJK characters
Creating unnecessary intermediate strings — poor space efficiency
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
publicclassPalindromeChecker {
/**
* 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
*/publicstaticbooleanisPalindrome(String input) {
if (input == null || input.isEmpty()) {
returntrue; // debatable — clarify with interviewer
}
intleft=0;
intright= input.length() - 1;
while (left < right) {
// Skip non-alphanumeric from leftwhile (left < right && !Character.isLetterOrDigit(input.charAt(left))) {
left++;
}
// Skip non-alphanumeric from rightwhile (left < right && !Character.isLetterOrDigit(input.charAt(right))) {
right--;
}
if (Character.toLowerCase(input.charAt(left)) !=
Character.toLowerCase(input.charAt(right))) {
returnfalse;
}
left++;
right--;
}
returntrue;
}
/**
* Strict palindrome check — considers all characters including spaces.
*/publicstaticbooleanisStrictPalindrome(String input) {
if (input == null || input.isEmpty()) {
returntrue;
}
Stringreversed=newStringBuilder(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;
importstatic org.junit.jupiter.api.Assertions.*;
classPalindromeCheckerTest {
@ParameterizedTest@ValueSource(strings = {"racecar", "RaceCar", "A man, a plan, a canal: Panama", "12321", ""})@DisplayName("Valid palindromes return true")voidshouldReturnTrueForPalindromes(String input) {
assertTrue(PalindromeChecker.isPalindrome(input));
}
@ParameterizedTest@ValueSource(strings = {"hello", "ab", "palindrome"})@DisplayName("Non-palindromes return false")voidshouldReturnFalseForNonPalindromes(String input) {
assertFalse(PalindromeChecker.isPalindrome(input));
}
@Test@DisplayName("Null input returns true")voidshouldReturnTrueForNull() {
assertTrue(PalindromeChecker.isPalindrome(null));
}
@Test@DisplayName("String with only special characters is palindrome")voidshouldHandleSpecialCharsOnly() {
assertTrue(PalindromeChecker.isPalindrome("!@#$%"));
}
@Test@DisplayName("Mixed case palindrome detected")voidshouldIgnoreCase() {
assertTrue(PalindromeChecker.isPalindrome("Aba"));
}
}
Common Mistakes
Allocating a new reversed string — wastes O(n) space when O(1) is possible
Not skipping non-alphanumeric characters — fails classic interview examples
Using == instead of comparing lowercase — case-sensitive comparison fails
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?
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;
publicclassDuplicateCounter {
/**
* 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
*/publicstaticMap<Character, Integer> countDuplicates(String input) {
if (input == null || input.isEmpty()) {
returnnewLinkedHashMap<>();
}
Map<Character, Integer> charCount=newLinkedHashMap<>();
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.
*/publicstaticMap<Character, Long> countDuplicatesStream(String input) {
if (input == null || input.isEmpty()) {
returnnewLinkedHashMap<>();
}
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)
Returning all characters instead of only duplicates — misreading the requirement
Not specifying case sensitivity upfront — clarify with interviewer
Using HashMap when order matters — use LinkedHashMap for deterministic output
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;
publicclassFirstUniqueCharFinder {
/**
* Finds the first non-repeating character using LinkedHashMap.
*
* @param input the string to search (nullable)
* @return Optional containing the first unique char, or empty
*/publicstaticOptional<Character> findFirstUnique(String input) {
if (input == null || input.isEmpty()) {
return Optional.empty();
}
LinkedHashMap<Character, Integer> charCount=newLinkedHashMap<>();
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.
*/publicstaticintfindFirstUniqueIndex(String input) {
if (input == null || input.isEmpty()) {
return -1;
}
int[] frequency=newint[256]; // ASCII assumptionfor (char c : input.toCharArray()) {
frequency[c]++;
}
for (inti=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)
Using HashMap (unordered) — loses insertion order, can't find "first"
Returning null instead of Optional — non-idiomatic, error-prone
Single pass approach that doesn't work — you need frequency info before deciding
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?
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;
publicclassDuplicateIdDetector {
/**
* Finds duplicate IDs in a list.
*
* @param ids list of IDs (nullable, may contain nulls)
* @return set of IDs that appear more than once
*/publicstatic <T> Set<T> findDuplicateIds(List<T> ids) {
if (ids == null || ids.isEmpty()) {
return Collections.emptySet();
}
Set<T> seen=newHashSet<>();
Set<T> duplicates=newLinkedHashSet<>(); // preserve discovery orderfor (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.
*/publicstatic <T> Map<T, List<Integer>> findDuplicatesWithIndices(List<T> ids) {
if (ids == null || ids.isEmpty()) {
return Collections.emptyMap();
}
Map<T, List<Integer>> indexMap=newLinkedHashMap<>();
for (inti=0; i < ids.size(); i++) {
Tid= ids.get(i);
if (id != null) {
indexMap.computeIfAbsent(id, k -> newArrayList<>()).add(i);
}
}
// Filter to only duplicates
indexMap.entrySet().removeIf(entry -> entry.getValue().size() < 2);
return indexMap;
}
/**
* Stream-based approach for functional style.
*/publicstatic <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
Using contains() on a List — O(n²) total time instead of O(n) with HashSet
Not handling null elements — NullPointerException in HashSet operations
Returning indices instead of IDs — misunderstanding the requirement
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?
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;
publicclassBalancedParentheses {
privatestaticfinalMap<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
*/publicstaticbooleanisBalanced(String input) {
if (input == null || input.isEmpty()) {
returntrue;
}
Deque<Character> stack=newArrayDeque<>();
for (char c : input.toCharArray()) {
if (BRACKET_PAIRS.containsValue(c)) {
// Opening bracket
stack.push(c);
} elseif (BRACKET_PAIRS.containsKey(c)) {
// Closing bracketif (stack.isEmpty() || !stack.pop().equals(BRACKET_PAIRS.get(c))) {
returnfalse;
}
}
// 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
Only counting open/close without matching type — "(]" wrongly passes
Using Stack class instead of ArrayDeque — Stack is legacy and synchronized
Not checking stack.isEmpty() before pop() — EmptyStackException
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)?
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.*;
publicclassIntervalMerger {
/**
* Merges overlapping intervals.
*
* @param intervals list of [start, end] pairs (nullable)
* @return merged intervals sorted by start time
*/publicstaticList<int[]> merge(List<int[]> intervals) {
if (intervals == null || intervals.isEmpty()) {
returnnewArrayList<>();
}
// Sort by start time
intervals.sort(Comparator.comparingInt(a -> a[0]));
List<int[]> merged=newArrayList<>();
int[] current= intervals.get(0);
merged.add(current);
for (inti=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.
*/publicstaticbooleanoverlaps(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)
Not sorting first — comparing non-adjacent intervals incorrectly
Using == instead of <= for overlap check — missing touching intervals
Not updating end with Math.max — fails when one interval contains another
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?
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
publicclassBinarySearch {
/**
* 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
*/publicstaticintsearch(int[] arr, int target) {
if (arr == null || arr.length == 0) {
return -1;
}
intleft=0;
intright= arr.length - 1;
while (left <= right) {
intmid= left + (right - left) / 2; // prevents overflowif (arr[mid] == target) {
return mid;
} elseif (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
/**
* Finds the first occurrence of target (for arrays with duplicates).
*/publicstaticintsearchFirst(int[] arr, int target) {
if (arr == null || arr.length == 0) {
return -1;
}
intleft=0;
intright= arr.length - 1;
intresult= -1;
while (left <= right) {
intmid= left + (right - left) / 2;
if (arr[mid] == target) {
result = mid;
right = mid - 1; // continue searching left
} elseif (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
Using (left + right) / 2 — integer overflow for large arrays
Using left < right instead of left <= right — misses single-element case
Setting right = mid or left = mid — infinite loop
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?
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
publicclassMissingNumberFinder {
/**
* 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
*/publicstaticintfindMissing(int[] nums) {
if (nums == null || nums.length == 0) {
return0;
}
intn= nums.length;
longexpectedSum= (long) n * (n + 1) / 2;
longactualSum=0;
for (int num : nums) {
actualSum += num;
}
return (int) (expectedSum - actualSum);
}
/**
* XOR approach — avoids potential overflow for very large n.
*/publicstaticintfindMissingXor(int[] nums) {
if (nums == null || nums.length == 0) {
return0;
}
intxor= nums.length; // start with nfor (inti=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;
importstatic org.junit.jupiter.api.Assertions.*;
classMissingNumberFinderTest {
@Test@DisplayName("Null array returns 0")voidshouldReturnZeroForNull() {
assertEquals(0, MissingNumberFinder.findMissing(null));
}
@Test@DisplayName("Missing number at start")voidshouldFindMissingAtStart() {
assertEquals(0, MissingNumberFinder.findMissing(newint[]{1, 2, 3}));
}
@Test@DisplayName("Missing number at end")voidshouldFindMissingAtEnd() {
assertEquals(3, MissingNumberFinder.findMissing(newint[]{0, 1, 2}));
}
@Test@DisplayName("Missing number in middle")voidshouldFindMissingInMiddle() {
assertEquals(2, MissingNumberFinder.findMissing(newint[]{0, 1, 3, 4}));
}
@Test@DisplayName("XOR approach matches sum approach")voidxorShouldMatchSumApproach() {
int[] nums= {0, 1, 3, 4, 5};
assertEquals(
MissingNumberFinder.findMissing(nums),
MissingNumberFinder.findMissingXor(nums));
}
}
Common Mistakes
Integer overflow with sum formula — use long for intermediate calculation
Sorting first — unnecessary O(n log n) when O(n) is possible
Using a HashSet — works but wastes O(n) space
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?
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.*;
publicclassStateTransitionValidator {
privatefinal Map<String, Set<String>> validTransitions;
publicStateTransitionValidator(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
*/publicValidationResultvalidate(List<String> states) {
if (states == null || states.size() <= 1) {
return ValidationResult.success();
}
for (inti=0; i < states.size() - 1; i++) {
Stringfrom= states.get(i);
Stringto= 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.
*/publicstaticclassValidationResult {
privatefinalboolean valid;
privatefinalint failureIndex;
privatefinal String message;
privateValidationResult(boolean valid, int failureIndex, String message) {
this.valid = valid;
this.failureIndex = failureIndex;
this.message = message;
}
publicstaticValidationResultsuccess() {
returnnewValidationResult(true, -1, "All transitions valid");
}
publicstaticValidationResultfailure(int index, String message) {
returnnewValidationResult(false, index, message);
}
publicbooleanisValid() { return valid; }
publicintgetFailureIndex() { return failureIndex; }
publicStringgetMessage() { return message; }
}
/**
* Factory method for common test lifecycle states.
*/publicstaticStateTransitionValidatortestLifecycle() {
Map<String, Set<String>> transitions=newHashMap<>();
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"));
returnnewStateTransitionValidator(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
Hardcoding transitions — use a configurable map for reusability
Only returning boolean — provide failure details for debugging
Not handling unknown states — NPE when looking up transitions
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.*;
publicclassArrayComparator {
/**
* 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
*/publicstatic <T> booleanequalIgnoringOrder(T[] arr1, T[] arr2) {
if (arr1 == arr2) returntrue;
if (arr1 == null || arr2 == null) returnfalse;
if (arr1.length != arr2.length) returnfalse;
Map<T, Integer> frequencyMap=newHashMap<>();
for (T item : arr1) {
frequencyMap.merge(item, 1, Integer::sum);
}
for (T item : arr2) {
intcount= frequencyMap.getOrDefault(item, 0);
if (count == 0) {
returnfalse; // element in arr2 not in arr1 (or exhausted)
}
frequencyMap.put(item, count - 1);
}
returntrue; // length check ensures no leftover in arr1
}
/**
* Primitive int array version.
*/publicstaticbooleanequalIgnoringOrder(int[] arr1, int[] arr2) {
if (arr1 == arr2) returntrue;
if (arr1 == null || arr2 == null) returnfalse;
if (arr1.length != arr2.length) returnfalse;
Map<Integer, Integer> freq=newHashMap<>();
for (int val : arr1) {
freq.merge(val, 1, Integer::sum);
}
for (int val : arr2) {
intcount= freq.getOrDefault(val, 0);
if (count == 0) returnfalse;
freq.put(val, count - 1);
}
returntrue;
}
}
Time/Space Complexity
Time Complexity: O(n) — two passes through the arrays
Space Complexity: O(n) — frequency map stores up to n entries
Sorting both arrays — O(n log n) when O(n) is possible; also mutates input
Using Set instead of frequency map — ignores duplicate counts
Not checking lengths first — unnecessary work when lengths differ
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)?
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;
publicclassAnagramGrouper {
/**
* 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
*/publicstaticList<List<String>> groupAnagrams(List<String> words) {
if (words == null || words.isEmpty()) {
returnnewArrayList<>();
}
Map<String, List<String>> groups=newHashMap<>();
for (String word : words) {
if (word == null) continue;
Stringkey= sortedKey(word);
groups.computeIfAbsent(key, k -> newArrayList<>()).add(word);
}
returnnewArrayList<>(groups.values());
}
/**
* Creates a canonical key by sorting characters.
*/privatestaticStringsortedKey(String word) {
char[] chars= word.toLowerCase().toCharArray();
Arrays.sort(chars);
returnnewString(chars);
}
/**
* Alternative: frequency-based key (avoids sorting for long strings).
*/privatestaticStringfrequencyKey(String word) {
int[] count=newint[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
Comparing every pair — O(n²) when grouping by key is O(n × k log k)
Not normalizing case — "Tea" and "eat" should be in the same group
Using the word itself as key — must use a canonical form (sorted chars)
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;
publicclassOrderPreservingDeduplicator {
/**
* Removes duplicates preserving first-occurrence order.
*
* @param items list with potential duplicates (nullable)
* @return new list with duplicates removed, order preserved
*/publicstatic <T> List<T> deduplicate(List<T> items) {
if (items == null || items.isEmpty()) {
returnnewArrayList<>();
}
Set<T> seen=newLinkedHashSet<>();
for (T item : items) {
seen.add(item); // LinkedHashSet maintains insertion order
}
returnnewArrayList<>(seen);
}
/**
* Stream-based approach using distinct().
*/publicstatic <T> List<T> deduplicateStream(List<T> items) {
if (items == null) returnnewArrayList<>();
return items.stream()
.distinct()
.collect(Collectors.toList());
}
/**
* Deduplicate by a key extractor (e.g., remove duplicate objects by ID).
*/publicstatic <T, K> List<T> deduplicateByKey(List<T> items,
java.util.function.Function<T, K> keyExtractor) {
if (items == null || items.isEmpty()) {
returnnewArrayList<>();
}
Set<K> seenKeys=newHashSet<>();
List<T> result=newArrayList<>();
for (T item : items) {
Kkey= 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
Using HashSet (loses order) — need LinkedHashSet or manual tracking
Using contains() on a List — O(n²) total vs. O(n) with Set
Modifying the input list — always return a new list
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
publicclassBasicEmailValidator {
/**
* 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
*/publicstaticbooleanisValid(String email) {
if (email == null || email.isBlank()) {
returnfalse;
}
// No leading/trailing whitespaceif (!email.equals(email.trim())) {
returnfalse;
}
// Exactly one @ symbolintatIndex= email.indexOf('@');
if (atIndex == -1 || atIndex != email.lastIndexOf('@')) {
returnfalse;
}
StringlocalPart= email.substring(0, atIndex);
Stringdomain= email.substring(atIndex + 1);
// Local part checksif (localPart.isEmpty() || localPart.length() > 64) {
returnfalse;
}
// Domain checksif (domain.isEmpty() || domain.length() > 253) {
returnfalse;
}
// Domain must contain at least one dotif (!domain.contains(".")) {
returnfalse;
}
// Domain cannot start or end with dot or hyphenif (domain.startsWith(".") || domain.endsWith(".")
|| domain.startsWith("-") || domain.endsWith("-")) {
returnfalse;
}
// No consecutive dots in domainif (domain.contains("..")) {
returnfalse;
}
// TLD must be at least 2 charactersStringtld= domain.substring(domain.lastIndexOf('.') + 1);
if (tld.length() < 2) {
returnfalse;
}
// No spaces anywhereif (email.contains(" ")) {
returnfalse;
}
returntrue;
}
/**
* Regex-based validation for comparison — more concise but less readable.
*/publicstaticbooleanisValidRegex(String email) {
if (email == null) returnfalse;
Stringpattern="^[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
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?
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;
publicclassSafeInputParser {
/**
* Parses comma-separated integers, skipping malformed entries.
*
* @param input comma-separated string (nullable)
* @return list of successfully parsed integers
*/publicstaticList<Integer> parseIntegers(String input) {
if (input == null || input.isBlank()) {
returnnewArrayList<>();
}
List<Integer> results=newArrayList<>();
String[] tokens= input.split(",");
for (String token : tokens) {
Stringtrimmed= 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.
*/publicstaticParseResultparseWithErrors(String input) {
if (input == null || input.isBlank()) {
returnnewParseResult(newArrayList<>(), newArrayList<>());
}
List<Integer> valid=newArrayList<>();
List<String> errors=newArrayList<>();
String[] tokens= input.split(",");
for (inti=0; i < tokens.length; i++) {
Stringtrimmed= 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));
}
}
returnnewParseResult(valid, errors);
}
publicrecordParseResult(List<Integer> values, List<String> errors) {
publicbooleanhasErrors() { return !errors.isEmpty(); }
}
/**
* Optional-based parsing for single values.
*/publicstaticOptional<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
Catching generic Exception — only catch NumberFormatException
Silently swallowing errors without option to report — provide error details
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?
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;
publicclassNullSafetyTester {
/**
* 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
*/publicstatic <T, R> booleanhandlesNull(Function<T, R> function) {
try {
function.apply(null);
returntrue; // null handled gracefully
} catch (NullPointerException e) {
returnfalse; // function is not null-safe
} catch (Exception e) {
returntrue; // other exceptions are acceptable (e.g., IllegalArgumentException)
}
}
/**
* Generates standard edge-case strings for testing.
*/publicstaticList<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.
*/publicstatic <T> List<List<T>> edgeCaseLists(T sampleElement) {
List<List<T>> cases=newArrayList<>();
cases.add(null);
cases.add(Collections.emptyList());
cases.add(Collections.singletonList(sampleElement));
cases.add(Collections.unmodifiableList(List.of(sampleElement)));
List<T> withNull=newArrayList<>();
withNull.add(null);
cases.add(withNull);
return cases;
}
/**
* Validates that a function returns a sensible default for null/empty inputs.
*/publicstatic <R> TestReportvalidateDefaults(
Function<String, R> function,
R expectedForNull,
R expectedForEmpty) {
List<String> failures=newArrayList<>();
try {
RnullResult= 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 {
RemptyResult= 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());
}
returnnewTestReport(failures.isEmpty(), failures);
}
publicrecordTestReport(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;
importstatic org.junit.jupiter.api.Assertions.*;
classNullSafetyTesterTest {
@Test@DisplayName("Detects null-safe function")voidshouldDetectNullSafeFunction() {
assertTrue(NullSafetyTester.handlesNull(s -> s == null ? "" : s.toString()));
}
@Test@DisplayName("Detects null-unsafe function")voidshouldDetectNullUnsafeFunction() {
assertFalse(NullSafetyTester.handlesNull((String s) -> s.length()));
}
@Test@DisplayName("Edge case strings include expected values")voidshouldGenerateEdgeCaseStrings() {
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")voidshouldValidateDefaults() {
varreport= NullSafetyTester.validateDefaults(
s -> s == null ? 0 : s.length(),
0, // expected for null0// expected for empty
);
assertTrue(report.passed());
}
@Test@DisplayName("Reports failure when defaults don't match")voidshouldReportFailure() {
varreport= NullSafetyTester.validateDefaults(
s -> s == null ? -1 : s.length(),
0, // expected 0 but function returns -10
);
assertFalse(report.passed());
assertEquals(1, report.failures().size());
}
}
Common Mistakes
Only testing null, not empty — empty string is a separate case from null
Not testing blank (whitespace-only) — often forgotten boundary
Confusing isEmpty() with isBlank() — Java 11+ distinction matters
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?
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.*;
publicclassMapVsSetDemo {
// ============ USE HASHSET WHEN ============// You only need to track membership (yes/no questions)/**
* HashSet example: Check if any element appears in a blocklist.
*/publicstaticbooleancontainsBlockedWord(List<String> words, Set<String> blocklist) {
// Set.contains() is O(1) — perfect for membership testingfor (String word : words) {
if (blocklist.contains(word.toLowerCase())) {
returntrue;
}
}
returnfalse;
}
/**
* HashSet example: Find unique elements.
*/publicstatic <T> intcountUnique(List<T> items) {
if (items == null) return0;
returnnewHashSet<>(items).size();
}
// ============ USE HASHMAP WHEN ============// You need to associate keys with values (lookup tables)/**
* HashMap example: Count frequency of elements.
*/publicstatic <T> Map<T, Integer> countFrequency(List<T> items) {
if (items == null) return Collections.emptyMap();
Map<T, Integer> frequency=newHashMap<>();
for (T item : items) {
frequency.merge(item, 1, Integer::sum);
}
return frequency;
}
/**
* HashMap example: Index objects by a key for fast lookup.
*/publicstatic <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=newHashMap<>();
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>>
*/
}
Using HashMap when only membership is needed — wastes memory on values
Using List.contains() instead of Set — O(n) vs O(1) per lookup
Forgetting that HashMap allows null keys — can cause subtle bugs
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?
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.*;
publicclassComplexityAnalysis {
// ============ O(1) — CONSTANT ============/**
* Array access, HashMap get, arithmetic operations.
*/publicstaticintgetElement(int[] arr, int index) {
// One operation regardless of array sizereturn arr[index]; // O(1)
}
// ============ O(log n) — LOGARITHMIC ============/**
* Binary search, balanced BST operations.
*/publicstaticintbinarySearch(int[] sorted, int target) {
intlo=0, hi = sorted.length - 1;
while (lo <= hi) {
intmid= lo + (hi - lo) / 2; // Each iteration halves the spaceif (sorted[mid] == target) return mid;
elseif (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.
*/publicstaticintfindMax(int[] arr) {
intmax= 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).
*/publicstaticint[] sortArray(int[] arr) {
int[] copy= arr.clone();
Arrays.sort(copy); // O(n log n) — dual pivot quicksortreturn copy;
}
// ============ O(n²) — QUADRATIC ============/**
* Nested loops, brute-force pair comparison.
*/publicstaticList<int[]> findAllPairs(int[] arr, int targetSum) {
List<int[]> pairs=newArrayList<>();
for (inti=0; i < arr.length; i++) { // n iterationsfor (intj= i + 1; j < arr.length; j++) { // n-1, n-2, ... iterationsif (arr[i] + arr[j] == targetSum) {
pairs.add(newint[]{arr[i], arr[j]});
}
}
}
return pairs; // O(n²)
}
// ============ SPACE COMPLEXITY EXAMPLES ============/**
* O(1) space — modifies in place or uses fixed variables.
*/publicstaticvoidreverseInPlace(int[] arr) {
intleft=0, right = arr.length - 1;
while (left < right) {
inttemp= 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.
*/publicstaticSet<Integer> toSet(int[] arr) {
Set<Integer> set=newHashSet<>(); // Grows with inputfor (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;
importstatic org.junit.jupiter.api.Assertions.*;
classComplexityAnalysisTest {
@Test@DisplayName("Linear search scales linearly")@Timeout(value = 1, unit = TimeUnit.SECONDS)voidlinearSearchShouldCompleteInTime() {
int[] large=newint[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)voidbinarySearchShouldBeLogarithmic() {
int[] sorted=newint[10_000_000];
for (inti=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")voidreverseInPlaceShouldModifyArray() {
int[] arr= {1, 2, 3, 4, 5};
ComplexityAnalysis.reverseInPlace(arr);
assertArrayEquals(newint[]{5, 4, 3, 2, 1}, arr);
}
@Test@DisplayName("Quadratic pair finder finds all pairs")voidshouldFindPairs() {
int[] arr= {1, 2, 3, 4, 5};
varpairs= ComplexityAnalysis.findAllPairs(arr, 5);
assertEquals(2, pairs.size()); // (1,4) and (2,3)
}
}
Common Mistakes
Saying "O(n)" for everything — analyze carefully, don't guess
Forgetting hidden costs — String += in a loop is O(n²)
Confusing space of output with extra space — output doesn't count
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?
Demonstrate techniques to prevent and detect integer overflow in Java. This is critical for financial calculations, array sizing, and test data generation.
Optimized Solution
publicclassOverflowPrevention {
// ============ DETECTION ============/**
* Safe addition that throws on overflow.
*/publicstaticintsafeAdd(int a, int b) {
return Math.addExact(a, b); // throws ArithmeticException on overflow
}
/**
* Safe multiplication that throws on overflow.
*/publicstaticintsafeMultiply(int a, int b) {
return Math.multiplyExact(a, b); // throws ArithmeticException on overflow
}
// ============ PREVENTION WITH LONG ============/**
* Use long for intermediate calculations.
*/publicstaticintaverageWithoutOverflow(int a, int b) {
// WRONG: (a + b) / 2 can overflow// RIGHT: use long for intermediate resultreturn (int) (((long) a + (long) b) / 2);
}
/**
* Binary search midpoint without overflow.
*/publicstaticintsafeMidpoint(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.
*/publicstaticbooleanwillOverflowOnAdd(int a, int b) {
if (b > 0 && a > Integer.MAX_VALUE - b) returntrue;
if (b < 0 && a < Integer.MIN_VALUE - b) returntrue;
returnfalse;
}
/**
* Safe sum of array using long accumulator.
*/publicstaticlongsafeSum(int[] arr) {
if (arr == null) return0L;
longsum=0L; // Use long to prevent overflowfor (int val : arr) {
sum += val;
}
return sum;
}
// ============ BIGINTEGER FOR ARBITRARY PRECISION ============/**
* For truly large numbers, use BigInteger.
*/publicstatic java.math.BigIntegerfactorial(int n) {
if (n < 0) thrownewIllegalArgumentException("n must be non-negative");
java.math.BigIntegerresult= java.math.BigInteger.ONE;
for (inti=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
"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.
*/publicclassTwoSum {
/**
* 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
*/publicstaticint[] findPair(int[] nums, int target) {
if (nums == null || nums.length < 2) {
returnnewint[]{};
}
Map<Integer, Integer> seen=newHashMap<>();
for (inti=0; i < nums.length; i++) {
intcomplement= target - nums[i];
if (seen.containsKey(complement)) {
returnnewint[]{seen.get(complement), i};
}
seen.put(nums[i], i);
}
returnnewint[]{};
}
}
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
Only testing happy path — missing null, empty, boundary cases
Hard-coding expected values without reasoning — tests become brittle
Not using @Nested for organization — flat test classes are hard to navigate
Testing implementation details — test behavior, not internal state
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?
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;
publicclassDuplicateEventHandler<T> {
privatefinal Map<String, Instant> processedEvents;
privatefinal Duration retentionWindow;
/**
* Creates handler with a time window for duplicate detection.
*
* @param retentionWindow how long to remember processed event IDs
*/publicDuplicateEventHandler(Duration retentionWindow) {
this.processedEvents = newConcurrentHashMap<>();
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
*/publicbooleantryProcess(String eventId) {
if (eventId == null || eventId.isBlank()) {
thrownewIllegalArgumentException("Event ID must not be null or blank");
}
Instantnow= Instant.now();
Instantprevious= processedEvents.putIfAbsent(eventId, now);
return previous == null; // null means it was new
}
/**
* Checks if an event has already been processed.
*/publicbooleanisDuplicate(String eventId) {
if (eventId == null) returnfalse;
Instantprocessed= processedEvents.get(eventId);
if (processed == null) returnfalse;
// Check if within retention windowif (Duration.between(processed, Instant.now()).compareTo(retentionWindow) > 0) {
processedEvents.remove(eventId);
returnfalse; // expired, treat as new
}
returntrue;
}
/**
* Cleans up expired entries to prevent memory growth.
*/publicintcleanup() {
Instantcutoff= Instant.now().minus(retentionWindow);
intremoved=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.
*/publicinttrackedCount() {
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
Using an unbounded Set — memory leak without cleanup/TTL
Not using thread-safe collections — events often arrive concurrently
Checking and inserting separately — race condition without putIfAbsent
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?
Implement a retry mechanism with exponential backoff and a maximum attempt cap. This is essential for testing flaky services, network calls, and asynchronous operations.
No backoff — hammering a failing service makes things worse
Not capping the delay — exponential growth leads to absurd waits
Sleeping after the last attempt — wasted time
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;
publicclassMultiFieldSorter {
/**
* Example domain object: a test result.
*/publicrecordTestResult(
String suiteName,
String status, // PASSED, FAILED, ERROR
long durationMs,
String testName
) {}
/**
* Sort test results by: status (FAILED first), then duration (desc), then name.
*/publicstaticList<TestResult> sortTestResults(List<TestResult> results) {
if (results == null || results.isEmpty()) {
returnnewArrayList<>();
}
// Define status priorityMap<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.
*/@SafeVarargspublicstatic <T> List<T> sortByFields(List<T> items, Comparator<T>... comparators) {
if (items == null || items.isEmpty()) {
returnnewArrayList<>();
}
if (comparators.length == 0) {
returnnewArrayList<>(items);
}
Comparator<T> combined= comparators[0];
for (inti=1; i < comparators.length; i++) {
combined = combined.thenComparing(comparators[i]);
}
return items.stream()
.sorted(combined)
.collect(Collectors.toList());
}
/**
* Sort with null-safe comparators.
*/publicstatic <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
Writing manual comparison logic — use Comparator.comparing().thenComparing()
Forgetting .reversed() for descending — natural order is ascending
Not handling nulls in fields — NPE during comparison
Mutating the input list — use stream().sorted() to return a new list
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?
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;
publicclassTopKFrequent {
/**
* 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)
*/publicstatic <T> List<T> findTopK(List<T> items, int k) {
if (items == null || items.isEmpty() || k <= 0) {
returnnewArrayList<>();
}
// Step 1: Count frequenciesMap<T, Integer> frequency=newHashMap<>();
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 = newPriorityQueue<>(
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=newArrayList<>();
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")publicstatic <T> List<T> findTopKBucketSort(List<T> items, int k) {
if (items == null || items.isEmpty() || k <= 0) {
returnnewArrayList<>();
}
// Count frequenciesMap<T, Integer> frequency=newHashMap<>();
for (T item : items) {
if (item != null) {
frequency.merge(item, 1, Integer::sum);
}
}
// Create buckets where index = frequencyList<T>[] buckets=newList[items.size() + 1];
for (Map.Entry<T, Integer> entry : frequency.entrySet()) {
intfreq= entry.getValue();
if (buckets[freq] == null) {
buckets[freq] = newArrayList<>();
}
buckets[freq].add(entry.getKey());
}
// Collect from highest frequency bucket downList<T> result=newArrayList<>();
for (inti= 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.
*/publicstatic <T> List<T> findTopKStream(List<T> items, int k) {
if (items == null || items.isEmpty() || k <= 0) {
returnnewArrayList<>();
}
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());
}
}
Sorting the entire frequency map — O(n log n) when O(n log k) is possible
Using a max-heap of size n — min-heap of size K is more efficient
Not handling ties — clarify with interviewer what to do
Forgetting null elements in the input — filter them out
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).
*/publicclassCodeReviewChecklist {
// ============ BEFORE REVIEW (common issues) ============/**
* PROBLEMATIC VERSION — multiple issues to catch in review.
*/publicstaticList<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 typesArrayListresult=newArrayList();
for (inti=0; i < data.size(); i++) {
try {
Strings= 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.
*/publicstaticList<String> processData(List<String> data) {
if (data == null || data.isEmpty()) {
returnnewArrayList<>(); // Issue 1: null/empty handled
}
List<String> uppercased=newArrayList<>(data.size()); // Sized appropriatelyfor (String item : data) { // Enhanced for-loop, no index neededif (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.
*/publicstaticStringjoinBad(List<String> items) {
Stringresult="";
for (String item : items) {
result += item + ","; // O(n²) — creates new String each iteration
}
return result;
}
/** Fixed: Use StringBuilder or String.join() */publicstaticStringjoinGood(List<String> items) {
if (items == null || items.isEmpty()) return"";
return String.join(",", items); // O(n)
}
/**
* Anti-pattern 2: Checking contains then get on map.
*/publicstaticStringlookupBad(Map<String, String> map, String key) {
if (map.containsKey(key)) { // First hash lookupreturn map.get(key); // Second hash lookup (redundant)
}
return"default";
}
/** Fixed: Use getOrDefault */publicstaticStringlookupGood(Map<String, String> map, String key) {
return map.getOrDefault(key, "default"); // Single lookup
}
/**
* Anti-pattern 3: Catching broad exceptions.
*/publicstaticintparseBad(String value) {
try {
return Integer.parseInt(value);
} catch (Exception e) { // Too broad — hides bugsreturn0;
}
}
/** Fixed: Catch specific exception */publicstaticOptionalIntparseGood(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
Not reviewing at all — submitting first draft without a second look
Only checking if it compiles — compilation ≠ correctness
Not tracing through with sample input — dry-run catches logic errors
Ignoring the "what if null" question — most NPEs are preventable
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?