AlgoViz

O(n log n) linearithmic time

easy 16 min

O(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

  1. 380lo
  2. 271
  3. 432
  4. 33
  5. 94
  6. 825
  7. 106hi
n = 7levels = ⌈log₂ 7⌉ = 3

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

    critical

    Quick 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.

    Wrong
    def partition(arr, lo, hi):    pivot = arr[hi]          # sorted input: worst case every time    ...
    Right
    import 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

    critical

    The 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.

    Wrong
    while i < len(left) and j < len(right):    ...return result                 # drops the tail of one run
    Right
    while i < len(left) and j < len(right):    ...result.extend(left[i:])result.extend(right[j:])return result
  • Using < instead of <= when merging

    major

    On 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.

    Wrong
    if left[i] < right[j]:     # ties go to the right run    result.append(left[i])
    Right
    if left[i] <= right[j]:    # ties go to the left run: stable    result.append(left[i])
  • Sorting inside a loop

    critical

    Re-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.

    Wrong
    data = []for x in stream:    data.append(x)    data.sort()               # O(n log n) every time
    Right
    import bisectdata = []for x in stream:    bisect.insort(data, x)    # O(log n) search + O(n) shift
  • Building a heap with n pushes

    minor

    Pushing 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.

    Wrong
    import heapqh = []for x in nums:    heapq.heappush(h, x)      # O(n log n) build
    Right
    import heapqh = list(nums)heapq.heapify(h)              # O(n) build
  • Recursing without a base case

    critical

    Merge sort and quick sort must stop at pieces of size 0 or 1. Without that check the recursion splits forever and Python raises RecursionError.

    Wrong
    def merge_sort(arr):    mid = len(arr) // 2    return merge(merge_sort(arr[:mid]), merge_sort(arr[mid:]))
    Right
    def 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).