Chapter 13

Algorithm Complexity & Big O Notation

FREE Big O Notation β€” Measuring Algorithm Efficiency
Article Β· 18 min
πŸ“ Homework

How do we compare algorithms? We use Big O notation β€” a way to describe how an algorithm's runtime grows as the input size grows.


Common Big O Runtimes

NotationNameExamplen=1000
O(1)ConstantArray access by index1 step
O(log n)LogarithmicBinary search~10 steps
O(n)LinearLinear search1000 steps
O(n log n)LinearithmicMerge sort~9966 steps
O(nΒ²)QuadraticBubble sort1,000,000 steps
O(2ⁿ)ExponentialFibonacci recursiveImpossible!
Steps (Operations) Input Size (n) 1 10 100 1K 10K
n =
10
β€”
Click a curve or legend item
Select a complexity class to see its details, example algorithm, and step count.
Practice 1
  1. What is the Big O of accessing any element in a Python list by index?
  2. What is the Big O of finding an element in a Python dictionary by key?
  3. If algorithm A takes O(n) and algorithm B takes O(nΒ²), which is faster for large inputs?

Determining Big O

Rules of thumb:

  • A single operation β†’ O(1)
  • A loop over n items β†’ O(n)
  • A loop that halves the input each time β†’ O(log n)
  • Nested loops β†’ multiply: O(n Γ— m)
  • Drop constants: O(2n) β†’ O(n)
  • Keep the dominant term: O(nΒ² + n) β†’ O(nΒ²)
# O(n) β€” single loop
for i in range(n):
    print(i)

# O(nΒ²) β€” nested loop
for i in range(n):
    for j in range(n):
        print(i, j)

# O(nΒ²) β€” even with constant factor
for i in range(n):
    for j in range(100):    # 100 is constant!
        print(i, j)
Practice 2
  1. What is the Big O of this code?
    for i in range(n):
        for j in range(i):
            print(i, j)
  2. What is the space complexity of an in-place bubble sort?