Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Recursive quicksort can need O(n) stack depth on adversarial input. Which change GUARANTEES O(log n) extra stack space even in the worst case?

  1. A. Pick the pivot uniformly at random
  2. B. Recurse only into the smaller partition and handle the larger one with a loop (tail-call elimination)
  3. C. Use median-of-three pivot selection
  4. D. Use three-way (Dutch flag) partitioning

Correct answer: B. Recurse only into the smaller partition and handle the larger one with a loop (tail-call elimination)

Each recursive call then gets at most half the current range, so depth is at most log₂ n regardless of pivot quality. Random pivots give O(log n) only in expectation, median-of-three can still be beaten by crafted input, and 3-way partitioning helps only with many duplicates.

More Coding Interview Problems questions

Exams that ask this topic