Skip to content

Lesson 1 of 40Foundations

Big-O Notation

Describe how fast code slows down as its input grows, and pick the right complexity for any common pattern.

16 min read0/5 questions

Two solutions both pass on 10 items. On 10 million items one finishes in a blink and the other runs until lunch. Big-O is the language engineers use to tell those apart before running anything, and it is the first thing an interviewer asks about after you write code.

What Big-O measures

Big-O does not measure seconds. Seconds depend on your laptop, the language, and what else is running. Big-O measures how the amount of work grows as the input grows.

The input size is called n: the length of a list, the number of characters in a string, the number of users. Big-O answers one question: if n doubles, what happens to the work?

Python
def count_steps(nums): steps = 0 for x in nums: steps += 1 return steps for n in [10, 20, 40, 80]: print(n, "items ->", count_steps(list(range(n))), "steps")
Output
Press Run (⌘ Enter) to see what happens.

Double the input, double the steps. That shape is called linear, written O(n). The exact count does not matter; the shape of the growth does.

Quick check
A function takes 2 seconds on your laptop. What is its Big-O?
Need a nudge? A hint rules out a wrong answer.

The common complexities

Here are the shapes you will see again and again, from best to worst, each with an everyday picture.

Big-ONameEveryday analogyCode example
O(1)constantOpening a book to a bookmarked pagenums[5], d["key"]
O(log n)logarithmicFinding a word in a dictionary by halvingbinary search
O(n)linearReading every page onceone loop over the list
O(n log n)linearithmicSorting a deck by splitting and merging pilessorted(nums)
O(n²)quadraticEveryone in a room shaking hands with everyonetwo nested loops
O(2ⁿ)exponentialTrying every on/off combination of n light switchesall subsets
O(n!)factorialTrying every seating order at a dinner tableall permutations

Drag the slider and watch the curves pull apart. Notice how O(n²) and O(2ⁿ) leave the chart almost immediately.

How work grows as input grows
input size n →ops
  • O(1)1
  • O(log n)4
  • O(n)16
  • O(n log n)64
  • O(n²)256
  • O(2ⁿ)66K

Logarithmic deserves a second look. log₂ n asks "how many times can I halve n before I reach 1?" For a million items that is only about 20. That is why binary search on a sorted list of a billion items needs about 30 checks.

Match the pairs0/6 matched

Match each task to its complexity.

Choose an item, then its match on the other side.

Build intuition with real numbers

A useful rule of thumb: a typical machine does roughly 10⁸ simple operations per second in a compiled language, and Python is often 10 to 50 times slower. This table shows approximate operation counts.

nlog nn log nn²2ⁿ
103331001,024
1,0001010,0001,000,000more than atoms in the universe
100,000171.7 million10 billionforget it
10,000,00023230 million10¹⁴forget it

Read it like this: at n = 100,000, an O(n log n) solution does about 1.7 million steps (instant), while O(n²) does 10 billion (minutes in Python). Interview problems often state limits like n ≤ 10⁵ exactly so you can work backwards: that limit is telling you O(n²) is too slow and O(n log n) or O(n) is expected.

Input limitWhat usually fits
n ≤ 10O(n!) or O(2ⁿ) brute force
n ≤ 20O(2ⁿ)
n ≤ 1,000O(n²)
n ≤ 10⁵ to 10⁶O(n log n) or O(n)
biggerO(log n) or O(1)
Quick check
A problem says 1 <= len(nums) <= 200,000. Your first idea uses two nested loops over nums. What should you do?
Need a nudge? A hint rules out a wrong answer.

Drop constants and smaller terms

Big-O keeps only the part that dominates when n is huge.

  • Drop constants. A loop that does 3 things per item is O(3n), which we write O(n). Two separate loops over the list are O(2n), still O(n).
  • Drop smaller terms. O(n² + n) is O(n²). When n is a million, n² is a trillion and the extra million is a rounding error.
  • Keep different inputs separate. Looping over list a then list b is O(a + b), not O(n). A loop over a nested inside a loop over b is O(a · b).
Python
def summary(nums): total = 0 for x in nums: # n steps total += x biggest = max(nums) # n more steps return total, biggest # O(2n) -> O(n) print(summary([4, 8, 15, 16, 23, 42]))
Output
Press Run (⌘ Enter) to see what happens.
Quick check
Simplify O(5n² + 300n + 9000).
Need a nudge? A hint rules out a wrong answer.

Best, average and worst case

The same code can do very different amounts of work depending on the input. Searching a list for a value:

  • Best case: the value is first. One check. O(1).
  • Worst case: the value is last or missing. n checks. O(n).
  • Average case: about n/2 checks on random input, which is still O(n).

When people say "linear search is O(n)" they mean the worst case, and that is the default in interviews. Mention average case when it differs in an interesting way: a hash map lookup is O(1) on average but O(n) in a pathological worst case, and quicksort is O(n log n) on average but O(n²) in the worst case.

Big-O, Big-Theta and Big-Omega

Formally there are three symbols.

  • Big-O is an upper bound: the work grows no faster than this.
  • Big-Omega (Ω) is a lower bound: the work grows at least this fast.
  • Big-Theta (Θ) is a tight bound: both at once.

Linear search is Θ(n) in the worst case and Ω(1) overall (the best case is instant). Strictly, it is also O(n²), because n² is a valid (loose) upper bound. In everyday engineering and in interviews, people say "Big-O" and mean the tight bound. Use it that way, and know the other two exist in case someone asks.

Space complexity

Big-O also describes memory: how much extra space your code needs as n grows. Count the new data structures you create, not the input you were given.

Python
def reverse_copy(nums): return nums[::-1] # new list of n items: O(n) space def reverse_in_place(nums): i, j = 0, len(nums) - 1 while i < j: # only two integers: O(1) space nums[i], nums[j] = nums[j], nums[i] i += 1 j -= 1 return nums print(reverse_copy([1, 2, 3]))print(reverse_in_place([1, 2, 3]))
Output
Press Run (⌘ Enter) to see what happens.

Often you can trade one for the other. A set of "seen" values costs O(n) memory but turns an O(n²) duplicate check into O(n) time. That trade is the heart of the next few lessons.

Match the pairs0/4 matched

What extra space does each piece of code use?

Choose an item, then its match on the other side.

How this course is laid out

  • Foundations give you Big-O, the core data structures and a method for any problem.
  • Core patterns and More array patterns cover hashing, two pointers, sliding windows, stacks, binary search, linked lists, prefix sums and grids.
  • Trees and graphs and Graphs in depth move from trees, tries and heaps to BFS, DFS, union-find, shortest paths and spanning trees.
  • Advanced patterns and DP families cover dynamic programming, greedy, intervals, bits and sorting, then the main DP shapes one by one.
  • Strings, math and design finishes with string algorithms, interview math, range queries and design problems like an LRU cache.

By the end you can look at a new problem, name the pattern, write it and state its cost. The course closes with a wrap-up that ties it all together.

ChallengeEasy

Sum 1 to n in constant time

Return the sum 1 + 2 + ... + n for a whole number n >= 0.

The loop version is O(n). Write an O(1) version: the same amount of work whether n is 10 or 10 billion.

n = 4    →  10
n = 100  →  5050
n = 0    →  0
def sum_to_n(n: int) -> int: # No loop. There is a formula. pass
Key terms
Big-O
How the work (or memory) an algorithm needs grows as the input size n grows, ignoring constants.
O(log n)
Logarithmic: the work grows by one step each time n doubles. Typical of halving, like binary search.
O(n²)
Quadratic: doubling n makes the work four times bigger. Typical of nested loops over the same input.
worst case
The input that makes the algorithm do the most work. The default meaning of a Big-O claim.
space complexity
How much extra memory an algorithm needs as n grows, not counting the input itself.