LearnFrenzy
Sign in Take a free test

Data Structures interview · Set 14 of 14

DSA Tricky Questions: Edge Cases and Complexity Traps

  • 6 follow-up questions
  • 4 key points
  • Code examples
Test yourself

Correct is not enough

Strong candidates test edge cases, watch for overflow and off-by-one errors, spot hidden quadratic costs and question greedy choices — before running out of time.

  • NumbersOverflow and midpoint calculation.
  • ComplexityHidden O(n²) and hash map caveats.
  • CorrectnessGreedy counterexamples and recursion depth.

Correct-looking code fails interviews because of edge cases and hidden costs. These questions train you to spot overflow, off-by-one errors, quadratic loops and wrong greedy assumptions before the interviewer does.

1. What is wrong with (lo + hi) / 2?

For large indexes, lo + hi can exceed Integer.MAX_VALUE and overflow to a negative number. Use lo + (hi - lo) / 2 or (lo + hi) >>> 1.


2. Why does this sum overflow, and how do you fix it?

Multiplying or summing ints can exceed 2³¹−1 silently. Use long for sums and products, or Math.addExact to fail loudly.

int n = 100_000;
int pairs = n * (n - 1) / 2;          // overflows → wrong (negative) result
long pairsOk = (long) n * (n - 1) / 2; // 4999950000

3. What is the hidden complexity of this loop?

O(n²). String += copies the whole string each time, and list.contains on an ArrayList scans it. Use StringBuilder and a HashSet to make it O(n).

String out = "";
for (String w : words) {
    if (!seen.contains(w)) {       // seen is an ArrayList: O(n) per check
        out += w + " ";            // copies the whole string: O(n) per append
        seen.add(w);
    }
}

4. Why does greedy fail for coin change {1, 3, 4} with amount 6?

Greedy takes 4 + 1 + 1 (three coins), but 3 + 3 (two coins) is optimal. Greedy works only when the coin system has the greedy-choice property; in general you need dynamic programming.


5. Why does sorting change the answer in “two sum returning indexes”?

Sorting reorders elements, so returned indexes no longer refer to the original array. Use a hash map (keeps original indexes), or sort index–value pairs.


6. Why can recursive DFS crash on a large input that works on small tests?

Each call uses stack space; a 10⁵-node linked-list-shaped tree or a big grid causes StackOverflowError. Use an explicit stack (iterative DFS) or BFS for very deep structures.


7. Which edge cases should you test for almost every problem?

  • Empty input and a single element.
  • All elements equal; duplicates.
  • Negative numbers and zero.
  • Already sorted and reverse-sorted input.
  • Maximum sizes and values (overflow, time limits).
  • For strings: spaces, case, Unicode, empty string.
  • For graphs: disconnected parts, cycles, self-loops.

8. Why is HashMap lookup “O(1)” not always true?

It is O(1) on average. With many collisions (bad hash functions or crafted keys) buckets grow; Java 8+ turns large buckets into trees for O(log n), but resizing still costs O(n) occasionally. Mention “amortised average O(1)”.


Remember

Key points

  • Use long for big sums

    Ints overflow silently.

  • String += in loops is O(n²)

    Use StringBuilder.

  • Prove greedy or use DP

    Test a small counterexample.

  • Deep recursion → iterate

    Avoid stack overflow.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 Why does Math.abs(Integer.MIN_VALUE) return a negative number? Advanced

    Its positive value does not fit in an int, so it overflows back to Integer.MIN_VALUE. Use long or Math.absExact.

  2. 2 What is wrong with comparing doubles using ==? Basic

    Rounding errors make equal-looking values differ; compare with a small tolerance.

  3. 3 Why can (a - b) as a comparator be a bug? Intermediate

    Subtraction can overflow for large values with different signs, giving the wrong sign; use Integer.compare(a, b).

  4. 4 What is the complexity of slicing a list in Python or substring in Java? Intermediate

    O(k) for the copied length — doing it inside a loop can make an algorithm quadratic.

  5. 5 Why should you mark visited when you enqueue in BFS, not when you dequeue? Intermediate

    Otherwise the same node can be added many times before it is processed, wasting time and memory.

  6. 6 Why does a memo keyed only by index give wrong answers sometimes? Advanced

    The state includes more than the index (for example remaining capacity); the memo key must include every parameter that affects the result.

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links