Skip to the solution
MediumDSA11 min read

How do merge sort and quicksort work?

323 views

The problem

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 that sorted (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.

  • dsa
  • sorting
  • divide-and-conquer
  • recursion

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonMerge sort with a trace of every merge
PythonQuicksort trace, and last vs middle pivot on sorted input

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 102 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you solve the Rotting Oranges problem with multi-source BFS?

Continue