Why is sorting O(n log n) — and how do you prove it's optimal?
Two questions a senior interviewer will press on. This is a guided walk-through — press Play on each figure, step at your own pace, and leave able to say the answer, not just recall it.
Comparison sorts have a proven floor
The one sentence to keep in your pocket — say it cleanly and stop:
sort / sort_byare comparison sorts, so they're O(n log n)."That's the whole answer. The rest of this page is why it's true and how to wield it — so that when an interviewer pushes, you have the proof, not just the claim. Two separate ideas are at play: where the n log n comes from in an actual algorithm, and why nothing can ever beat it.
Where the n log n comes from
Forget formulas for a second. Run an actual comparison sort — merge sort — and the n log n falls out of its shape: a handful of passes, each one a single sweep across the data.
log₂n passes × n work per pass = n log n. That's the upper bound — proof a sort this fast exists. Next: proof you can't do better.
Why nothing beats it: the decision tree
Here's the proof, and it's the part that makes you sound senior. Any comparison sort is really a tree of yes/no questions. Counting the leaves gives the floor.
Is your problem as hard as sorting?
The decision tree bounds sorting. But your interview problem is merge-intervals. The elegant move: show your problem could be used to sort — so it inherits sorting's floor.
Optimal = match the floor
You don't prove optimality by enumerating every possible algorithm. You prove a lower bound and check whether your algorithm touches it. Two numbers, done.
Same problem, different floor
The lower bound isn't a property of the problem name — it's a property of the input. Flip the assumption and watch the floor move. This is why "is it sorted?" is a great question to ask up front.
The interview cheat-sheet
sort/sort_by are comparison sorts → O(n log n), worst and average.sort is a comparison sort, so the safe, correct answer stays O(n log n). Only mention radix if an interviewer explicitly asks "can you beat n log n?"