O(n log n) linearithmic time
easy 16 minO(n log n) is linear work repeated a logarithmic number of times: n work on each of log n levels.
See it run
Sort [38, 27, 43, 3, 9, 82, 10] three ways and watch n work repeat across log n levels, then see how far n log n stays below n².
Operations
Merge sort
Split [38, 27, 43, 3, 9, 82, 10] in half until every piece has one cell, then merge sorted pieces back together. log n levels, n work per level.
Step 1 of 11
Seven cells to sort
- 380lo
- 271
- 432
- 33
- 94
- 825
- 106hi
Merge sort is divide and conquer: split the array in half, sort each half the same way, then merge the two sorted halves. Halving 7 cells down to single cells takes \lceil \log_2 7 \rceil = 3 levels.
Step 1: Seven cells to sort
def merge_sort(arr, lo, hi): if lo >= hi: # one cell: already sorted return mid = (lo + hi) // 2 merge_sort(arr, lo, mid) # sort the left half merge_sort(arr, mid + 1, hi) # sort the right half merge(arr, lo, mid, hi) # O(n) combinedef merge(arr, lo, mid, hi): left, right = arr[lo:mid + 1], arr[mid + 1:hi + 1] i = j = 0 k = lo while i < len(left) and j < len(right): if left[i] <= right[j]: # <= keeps equal items in order arr[k] = left[i] i += 1 else: arr[k] = right[j] j += 1 k += 1 arr[k:hi + 1] = left[i:] + right[j:] # copy the leftovers- Time
- O(n log n) always
- Space
- O(n)
- bubble sort
- O(n²): up to 21 comparisons for 7
- this run
- 14 comparisons
Say it as a picture: a tree of log n levels, and each level touches all n items once while merging. That is n log n, on every input.
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Calling quick sort O(n log n) without a caveat
criticalQuick sort is O(n log n) only on average. A fixed first or last pivot on already sorted input gives splits of 0 and n - 1 every time, which is O(n²) and recursion n deep.
Wrongdef partition(arr, lo, hi): pivot = arr[hi] # sorted input: worst case every time ...Rightimport randomdef partition(arr, lo, hi): r = random.randint(lo, hi) arr[r], arr[hi] = arr[hi], arr[r] # random pivot: O(n log n) expected pivot = arr[hi] ...Forgetting the leftovers after a merge
criticalThe merge loop stops as soon as one run is empty. Whatever is left in the other run is already sorted and larger than everything placed, but it must still be copied, or values silently disappear.
Wrongwhile i < len(left) and j < len(right): ...return result # drops the tail of one runRightwhile i < len(left) and j < len(right): ...result.extend(left[i:])result.extend(right[j:])return resultUsing < instead of <= when merging
majorOn a tie, taking from the right run first lets an equal item jump ahead of one that came before it. The output is still sorted, but merge sort loses stability, which breaks multi-key sorts.
Wrongif left[i] < right[j]: # ties go to the right run result.append(left[i])Rightif left[i] <= right[j]: # ties go to the left run: stable result.append(left[i])Sorting inside a loop
criticalRe-sorting the whole list after every insert costs O(n log n) each time, so n inserts cost O(n² log n). Keep the list sorted with bisect.insort, or use a heap.
Wrongdata = []for x in stream: data.append(x) data.sort() # O(n log n) every timeRightimport bisectdata = []for x in stream: bisect.insort(data, x) # O(log n) search + O(n) shiftBuilding a heap with n pushes
minorPushing n items one at a time is O(n log n). heapq.heapify sifts down from the last parent and builds the same heap in O(n). The sort is still O(n log n), but the build step is cheaper.
Wrongimport heapqh = []for x in nums: heapq.heappush(h, x) # O(n log n) buildRightimport heapqh = list(nums)heapq.heapify(h) # O(n) buildRecursing without a base case
criticalMerge sort and quick sort must stop at pieces of size 0 or 1. Without that check the recursion splits forever and Python raises RecursionError.
Wrongdef merge_sort(arr): mid = len(arr) // 2 return merge(merge_sort(arr[:mid]), merge_sort(arr[mid:]))Rightdef merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 return merge(merge_sort(arr[:mid]), merge_sort(arr[mid:]))
Interview tips
How to explain it
- O(n log n) is linear work repeated a logarithmic number of times: n work per level, log n levels.
- Merge sort's recurrence T(n) = 2T(n/2) + O(n) solves to O(n log n).
- It is the best any comparison sort can do: log₂(n!) ≈ n log₂ n comparisons are needed in the worst case.
- n log n is only log n times more than linear: about 20 times at a million items.
Spot it in code
- Any call to `sorted()` or `.sort()`: O(n log n).
- Split in half, recurse on both halves, combine in O(n).
- A loop of n heap pushes or pops, or n binary searches.
- Sort first, then a linear scan: O(n log n) + O(n) = O(n log n).
Memory tricks
- n work × log n levels = n log n total.
- Tree height: a balanced recursion tree has log n levels.
- Divide and conquer: split, solve, combine.
- Sort smart: merge is safe, quick is fast, heap is lean.
Watch out
- Quick sort's worst case is O(n²); say average O(n log n).
- Merge sort needs O(n) extra memory; heap sort needs O(1) but is not stable.
- Recursing on only one half is not n log n: T(n) = T(n/2) + O(n) is O(n).