Skip to the solution
MediumDSA13 min read

How does Timsort make Python's sort fast and stable?

436 views

The problem

Question presented to candidate: "Python's sorted() and list.sort() use an algorithm called Timsort. How does it work, why is it so fast on real-world data, and why is it guaranteed to be stable? What is its complexity?"

What a strong answer should cover:

  • Timsort is a hybrid, adaptive, stable merge sort designed by Tim Peters for CPython (2002): it exploits order that already exists in the data
  • It scans for natural runs (non-descending, or strictly descending which it reverses in place), extends short runs to minrun (32-64 elements) with binary insertion sort, and merges neighbouring runs
  • The merge order keeps runs balanced; since CPython 3.11 it follows the powersort rule (bpo-34561) instead of the original stack invariants; merges use galloping when one run keeps winning
  • Complexity: O(n log n) worst case, O(n) best case (about n - 1 comparisons on sorted or reversed input), O(n) extra memory for merging
  • Stability comes from never moving an element past an equal one: runs are only reversed when strictly descending, and merges take from the left run on ties; that enables multi-pass sorts by several keys
  • Only < is ever used, and the key function is called exactly once per element

Code / implementation expected: Optional β€” counting comparisons on sorted vs shuffled data, or sketching run detection and merging.

  • sorting
  • timsort

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

13 min read Β· 10 sections

Run the code

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

PythonCounting comparisons, and what stability buys you
PythonA toy Timsort: runs, minrun, insertion sort and powersort merging

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 93 of 139 in Python

Keep your momentum going.

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

All Python questions
Up nextMedium

What is the memory difference between a list comprehension and a generator expression?

Continue