Big-O notation — measuring how code scales
Big-O — the shape of your algorithm
Big-O describes how the work grows as the input grows. It's the single most-asked interview concept because it separates "this works on my laptop" from "this works at 100 million users."
The classes you must know
| Notation | Name | Feels like |
|---|---|---|
O(1) | Constant | Dictionary lookup, array indexing |
O(log n) | Logarithmic | Binary search |
O(n) | Linear | Single loop over a list |
O(n log n) | Log-linear | Merge sort, Python's sorted() |
O(n²) | Quadratic | Nested loop over the same list |
O(2ⁿ) | Exponential | Naïve recursive Fibonacci |
O(n!) | Factorial | Brute-force permutations |
Rules of thumb
- Drop constants.
O(3n)isO(n). Constants matter in practice but not in classification. - Drop lower-order terms.
O(n² + n)isO(n²). - Different inputs → different variables.
O(n + m)when two collections have unrelated sizes. - Amortized vs worst case. Python
list.append()is amortizedO(1)— occasionallyO(n)when it resizes.
Space complexity
Same idea for memory. A recursive function has O(depth) extra space on the call stack. A copy of a list is O(n) space.
The interview shortcut
Any nested loop over the same input → suspect O(n²). See if a hash map can turn it into O(n). This one substitution fixes 40% of "brute force → optimal" interview transitions.
Try it
- Change the starter to time a list of 10 million ints. The list-scan gets ~10× slower; set lookup stays flat.
- Write a function that finds duplicates in a list. First in
O(n²)(nested loops), then inO(n)(using a set).
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
- Exercise 1
Write two lookup functions that show the difference between O(n) and O(1).
contains_slow(nums, target)scans a list linearly.contains_fast(nums_set, target)checks membership in aset. Test both with[1, 2, 3, 4, 5]and target4. Print twoTruelines. - Exercise 2
Write
has_duplicates(nums)returning True if any value repeats. Do it in O(n) using a set — no nested loop. Printhas_duplicates([1, 2, 3, 4])(False) andhas_duplicates([1, 2, 3, 2])(True). - Exercise 3
Write
sum_of_pairs(nums)returning sum of all pairs(i, j)withi < jin O(n) via math trick: each element appears inn - 1pairs, so total issum(nums) * (n - 1). Printsum_of_pairs([1, 2, 3])— expected12.