Chapter 2 · Foundations

Big O Notation

A mathematical shorthand for describing how an algorithm's cost grows as input gets larger. It's the language engineers use to compare algorithms without benchmarking on specific hardware.

What is Big-O notation?

Big-O notation describes how the running time (or memory) of an algorithm grows as the input size n grows, ignoring constants. O(1) stays the same regardless of size, O(log n) grows very slowly, O(n) grows in proportion to the input, and O(n²) grows with its square, so doubling the input makes it four times slower.

arr[5];                        // O(1)     constant
binarySearch(sorted, x);       // O(log n) halves the search each step
arr.includes(x);               // O(n)     looks at every item
for (a of arr) for (b of arr); // O(n²)    nested loops
arr.sort();                    // O(n log n)

Why notation instead of milliseconds?

A function that takes 2ms on your laptop may take 0.5ms on a server or 20ms on a phone. Milliseconds lie. What we really want to know is: if the input doubles, does the time stay flat, double, or explode quadratically? Big O answers that question.

0

input size

0

O(n) operations

0

O(n²) operations

🔍Input size 1,000 — the difference is a million times
When n = 1,000, an O(n) algorithm does 1,000 operations. An O(n²) algorithm does 1,000,000. At n = 1,000,000 the O(n²) algorithm does 10¹² operations — the entire observable universe contains roughly 10⁸ atoms. Your algorithm would never finish.

The complexity classes

Constant — hash map lookup, array index accessO(1)

Constant time

Logarithmic — binary search, balanced BST operationsO(log n)

Logarithmic time

Linear — unsorted search, single pass through listO(n)

Linear time

Linearithmic — merge sort, heap sortO(n log n)

Linearithmic time

Quadratic — bubble sort, naive nested loopsO(n²)

Quadratic time

Exponential — brute-force subsets, naive recursive fibO(2ⁿ)

Exponential time

Interactive growth visualiser

Drag the slider to change n and watch how each complexity class grows. Notice how O(n²) explodes while O(log n) barely moves.

n =

16
O(1)
1
O(log n)
4
O(n)
16
O(n log n)
64
O(n²)
256

How to derive Big O from code

Three rules cover 90% of cases. Ignore constants, ignore lower-order terms, and look for nested loops.

how-to-count.pseudo
1Rule 1: Drop constants
2 f(n) = 3n + 7 → O(n) // 3 × linear is still linear
3 f(n) = 5n² + 2n → O(n²) // dominant term wins
4 
5Rule 2: Single loop = O(n)
6 for each item in collection: // O(n)
7 do constant work
8 
9Rule 3: Nested loops = multiply
10 for i from 0 to n: // O(n)
11 for j from 0 to n: // × O(n)
12 do constant work // = O(n²)
13 
14Rule 4: Halving each step = O(log n)
15 while size > 1: // cuts in half each time
16 size = size / 2 // e.g. 1024 → 512 → 256 → … → 1 in 10 steps

Worked examples

O(n)

Find max in unsorted list

Must examine every element once — can’t skip anything when there’s no order guarantee.

O(log n)

Binary search in sorted list

Each comparison eliminates half the remaining search space. 1,024 elements needs at most 10 comparisons.

O(n + m)

Check if two sorted lists share any value

Two-pointer technique: advance one pointer at a time through both lists. One pass each.

O(n²)

Print all pairs from n items

Outer loop picks first item (n choices), inner loop picks second (n-1 choices). n × (n-1) ≈ n².

O(n)

Insert into sorted position

Finding the position is O(log n), but shifting elements to make room is O(n) — the dominant term wins.

Space complexity

Big O describes memory usage too. An algorithm that allocates an n-element auxiliary array uses O(n) space. One that operates in-place uses O(1) space.

space-examples.pseudo
1// O(1) space — only a few variables regardless of n
2sumAll(arr):
3 total = 0
4 for each x in arr: total += x
5 return total
6 
7// O(n) space — create a copy of the input
8reversed(arr):
9 copy = new array of size n
10 for i from 0 to n-1: copy[i] = arr[n-1-i]
11 return copy
12 
13// O(n) space — recursion stack depth
14factorial(n):
15 if n = 0: return 1
16 return n × factorial(n-1) // n frames on call stack

Common misconceptions

O(n²) is always slow

For n = 100, n² = 10,000 operations. Runs in microseconds. Size matters — Big O tells you the growth rate, not the absolute time.

O(1) means instant

A hash map lookup is O(1) but involves hashing, memory access, and potential collision handling. It could still be slower than a 10-element linear scan in practice.

Best to always use O(log n) over O(n)

Binary search requires sorted data and random access (no linked lists). Maintaining sorted order often costs O(n log n). Sometimes a linear scan is genuinely better.

Big O is the only thing that matters

Constants, cache behaviour, branch prediction, and memory allocation all affect real-world performance. Big O is a starting point, not the final answer.

🎯 Quick Check

Algorithm A runs in O(n²). Algorithm B runs in O(n log n). For which input size does it first make sense to switch from A to B?

🧠The mental model to keep forever
Whenever you write a loop inside a loop, your antenna should go up: “is this O(n²)?” Whenever you see a problem that halves the search space each step, it’s O(log n). These two patterns account for the vast majority of algorithm analysis in interviews and real code.

Big-O Notation: summary

Key points

  • Big-O describes the worst case by default and ignores constants: O(2n) is O(n).
  • Keep only the fastest-growing term: O(n² + n) is O(n²).
  • Nested loops over the same data usually mean O(n²); halving the problem each step means O(log n).
  • Space complexity uses the same notation for extra memory.

Common mistakes

  • Forgetting hidden loops: includes, indexOf and splice are O(n), so calling them inside a loop is O(n²).

Frequently asked questions

›What is the difference between O(n) and O(log n)?

O(n) checks every item, so a million items means about a million steps. O(log n) halves the work each step, so a million items need only about 20 steps.

›Is O(1) always faster than O(n)?

For large inputs, yes. For tiny inputs, constants matter, and an O(n) loop over 5 items can beat a complex O(1) structure.

›What are Big-O, Big-Omega and Big-Theta?

Big-O is an upper bound, Big-Omega a lower bound, and Big-Theta a tight bound. In interviews, "Big-O" usually means the worst-case growth rate.