Skip to content
BytePatterns

Comparing Complexities

Big-O: lesson 5 of 5

O(n log n) beats O(n²) long before you notice.

Lesson 5 of 5 · 5 min

Comparing Complexities

Step 1 of 7

Same axes, same input. Watch how far apart the classes drift before n even gets interesting.

The Idea

The usual ranking runs O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2ⁿ). Small inputs hide the gaps between them. Real data exposes those gaps immediately.

Real-World Example

A route planner that compares every pair of stops handles a ten-stop day just fine. Give it a thousand deliveries and it grinds for hours, while an O(n log n) planner answers before the driver finishes their coffee.

The Code

import math

n = 1_000_000
print(1)                      # O(1)       -> 1
print(int(math.log2(n)))      # O(log n)   -> 19
print(n)                      # O(n)       -> 1000000
print(int(n * math.log2(n)))  # O(n log n) -> ~19931568
print(n * n)                  # O(n^2)     -> 1000000000000
# Same input. Wildly different bills.

Python

Your turn

Put the steps in the right order.

  1. O(n²)
  2. O(1)
  3. O(n log n)
  4. O(log n)
  5. O(n)

Mini quiz

1 / 3

Which of these grows fastest as n increases?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.