AlgoViz

Time complexity compared

easy 18 min

The seven common time complexities in one place: 1 < log n < n < n log n < n² < 2ⁿ < n!.

See it run

Tour all seven classes on one chart from the flat line to the explosion, pit them against each other in pairs, then turn the curves into a one-second budget and a constraint guide.

Operations

The tour: flat line to explosion

Add the seven classes to one growth chart in order, from O(1) to O(n!), and watch each new curve make the previous ones look flat.

Step 1 of 9

Seven classes at n = 5

n →ops200n = 5
  • O(1)1
  • O(\log n)2.3
  • O(n)5
  • O(n \log n)11.6
  • O(n^2)25
  • O(2^n)32
  • O(n!)120

at n = 5 every class still fits on one chart

Here are all seven curves at a tiny input, n = 5: 1, 2.3, 5, 12, 25, 32 and 120 operations. At this size they look like neighbours. The rest of the tour shows how quickly that changes as n grows.

Step 1: Seven classes at n = 5

import mathCLASSES = {    "O(1)":       lambda n: 1,    "O(log n)":   lambda n: math.log2(n),    "O(n)":       lambda n: n,    "O(n log n)": lambda n: n * math.log2(n),    "O(n^2)":     lambda n: n ** 2,    "O(2^n)":     lambda n: 2 ** n,    "O(n!)":      lambda n: math.factorial(n),}for n in (5, 20):    for name, f in CLASSES.items():        print(f"n = {n:>2}  {name:<11} {f(n):>26,.0f}")
Time
O(1) … O(n!)
Space
O(1)
n = 20, O(n²)
400 steps
n = 20, O(n!)
2.4 × 10¹⁸ steps

Learn the ladder in order: 1 < log n < n < n log n < n² < 2ⁿ < n!. Each rung beats every rung above it once n is large enough.

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • A hidden O(n) inside a loop

    critical

    x in some_list scans the whole list, so a loop that does it n times is O(n²) even though it looks like a single loop. A set lookup is O(1) on average.

    Wrong
    seen = []for x in nums:    if x in seen:        # O(n) scan each time        return True    seen.append(x)
    Right
    seen = set()for x in nums:    if x in seen:        # O(1) average        return True    seen.add(x)
  • Popping from the front of a list

    major

    list.pop(0) shifts every remaining element left, which is O(n). Draining a list that way is O(n²). A deque removes from either end in O(1).

    Wrong
    queue = list(range(n))while queue:    item = queue.pop(0)     # O(n) shift each time
    Right
    from collections import dequequeue = deque(range(n))while queue:    item = queue.popleft()  # O(1)
  • Shipping an exponential recursion

    critical

    Naive recursive Fibonacci makes two calls per level, about 2ⁿ calls in total. It looks fine at n = 10 and never finishes at n = 60. Caching each answer makes it O(n).

    Wrong
    def fib(n):    if n < 2:        return n    return fib(n - 1) + fib(n - 2)   # O(2^n)
    Right
    from functools import cache@cachedef fib(n):    if n < 2:        return n    return fib(n - 1) + fib(n - 2)   # O(n)
  • Keeping constants and smaller terms

    minor

    Big O describes growth, so only the fastest-growing term matters and constant factors are dropped. 3n² + 5n + 2 is simply O(n²).

    Wrong
    # cost: O(3n^2 + 5n + 2)for i in range(n):    for j in range(n):        work(i, j)
    Right
    # cost: O(n^2), the n^2 term dominatesfor i in range(n):    for j in range(n):        work(i, j)
  • Multiplying loops that run one after another

    major

    Two loops in sequence add their costs; only nested loops multiply. One pass over a and one over b is O(n + m), not O(n · m).

    Wrong
    for x in a: handle(x)for y in b: handle(y)# claimed: O(n * m)
    Right
    for x in a: handle(x)for y in b: handle(y)# actual: O(n + m)
  • Thinking the base of an exponential does not matter

    major

    The base of a logarithm does not matter, because logs differ by a constant factor. The base of an exponential does: 3ⁿ = 1.5ⁿ · 2ⁿ, and 1.5ⁿ is not a constant, so O(3ⁿ) is strictly worse than O(2ⁿ).

    Wrong
    # three recursive calls per level# "3^n is the same class as 2^n"
    Right
    # three recursive calls per level: O(3^n)# 3^n / 2^n = 1.5^n grows without bound

Interview tips

  • How to explain it

    • Big O describes how the work grows as n grows, ignoring constants and smaller terms.
    • The common order is 1 < log n < n < n log n < n² < 2ⁿ < n!.
    • At n = 1,000,000 that is 1, 20, a million, 20 million, a trillion, and two numbers too big to ever finish.
    • Name the class, then say what n it can handle in about a second.
  • Read the constraints

    • n ≤ 11: O(n!) is fine. n ≤ 25: O(2ⁿ).
    • n ≤ 500: O(n³). n ≤ 10⁴: O(n²).
    • n ≤ 10⁶: O(n log n) or O(n).
    • n up to 10¹⁸: O(log n) or O(1), so binary search or a formula.
  • Memory tricks

    • ONE operation, ONE time. LOG = LOOKUP Or GUESS. N = Navigate through N items.
    • N LOG N = Need to Look at everything, Organise by Groups.
    • N SQUARED = Need SQUARES (an n × n grid). 2 to the N = TWO choices per item.
    • FACTORIAL = Figure out ALL Choices.
  • Watch out

    • A single loop can hide O(n) work inside: `in` on a list, `pop(0)`, slicing, string building.
    • For small n a simple O(n²) can beat a clever O(n log n) because of constants.
    • Average and worst case can differ: quicksort is O(n log n) on average but O(n²) in the worst case.