Big-O: how to tell if your code will survive a million users
Big-O describes how the work grows as the input grows. The six classes you'll see in every interview, how to read them from code, and the rules for adding and dropping terms.
In short
Big-O answers "if the input doubles, what happens to the work?" It ignores constants and keeps the fastest-growing term: O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2ⁿ).
The idea: growth, not speed
Two programs can both take 10 ms on your laptop. With 1,000,000 items, one still takes milliseconds and the other takes hours. Big-O is the tool that tells them apart before you find out in production.
Reading Big-O from code
| Code shape | Complexity | Why |
|---|---|---|
| A fixed number of steps | O(1) | Doesn't depend on n: arr[5], map.get(key) |
| Halve the problem each step | O(log n) | Binary search, balanced trees |
| One loop over the input | O(n) | Each element is touched a constant number of times |
| Sort, or divide and merge | O(n log n) | log n levels, n work per level |
| A loop inside a loop | O(n²) | Every pair of elements |
| Try every subset or choice | O(2ⁿ) | Each element doubles the options |
- Sequential steps add: a loop then another loop is O(n + n) = O(n).
- Nested steps multiply: a loop inside a loop is O(n × n) = O(n²).
- Drop constants and smaller terms: O(3n + 50) is O(n); O(n² + n) is O(n²).
- Different inputs keep different letters: looping over
athen overbis O(a + b), not O(n).
Space complexity counts too
Space complexity is the extra memory your algorithm needs, not counting the input. A hash map with every element is O(n) space; two pointers is O(1). Recursion uses space too: every pending call sits on the call stack.
From constraints to the target complexity
Interview problems often state the input size. With roughly 10⁸ simple operations per second, the constraint tells you what complexity is expected:
| n up to | You probably need |
|---|---|
| 10–20 | O(2ⁿ) or O(n!) is fine: backtracking |
| 1,000–5,000 | O(n²) is fine |
| 100,000–1,000,000 | O(n log n) or O(n) |
| 10⁹ or more | O(log n) or O(1): math or binary search |
Key takeaways
- 01Big-O describes how work grows with input size, ignoring constants.
- 02Sequential steps add, nested steps multiply; keep only the biggest term.
- 03Always give both time and extra space complexity.
- 04The input size in the constraints hints at the complexity you need.
Check your understanding
1 of 3
What's the complexity of a loop over the array followed by another loop over the same array?
Related topics
Recursion
A recursive function solves a problem by calling itself on a smaller version of it, until it reaches a base case it can answer directly. Each pending call waits on the call stack, so recursion costs memory too.
8 min read →Binary search
If the data is sorted (or the answer is monotonic), look at the middle and throw away the half that can't contain the answer. Each step halves the problem: O(log n).
9 min read →