Question presented to candidate: "Explain how merge sort and quicksort work โ walk me through each on a small array โ and then implement one of them in Python. What are their time and space costs, and when does quicksort go wrong?"
What a strong answer should cover:
- Both are divide and conquer; merge sort does its work in the merge, quicksort in the partition.
- Merge sort: split at the middle, recurse, two-pointer merge; O(n log n) in every case, O(n) extra space, stable because ties come from the left.
- Quicksort: pivot, partition (Lomuto or Hoare), recurse on both sides; O(n log n) average, O(nยฒ) worst case, O(log n) average stack, not stable.
- Explains the worst case (sorted input with a first/last pivot) and the fixes: random or median-of-three pivot, introsort, recursing on the smaller side.
- Python specifics: slices copy (O(n) extra memory),
//for the midpoint, CPython's 1000-frame recursion limit, and thatsorted(Timsort) is the production answer.
Clarifying questions expected:
- Should the sort be in place, or may I use extra memory?
- Does it need to be stable?
Code / implementation expected: Yes โ a working Python merge sort or quicksort, with the base case and the merge or partition step correct.