Big-O and complexity analysis
Big-O says how time or memory grows with input size, ignoring constants: before coding, name n, state time and space, and check them against the input limits.
Analogy: Mailing one invitation per guest is O(n); every guest shaking hands with every other is O(n²). Double the guests and the handshakes quadruple.
How it works
- Drop constants and lower-order terms:
3n² + 10nis O(n²). Quote the worst case unless told otherwise. - Sequential steps add, nested loops multiply, and halving the search space each step gives log n.
- Count space too: the extra memory you allocate, including the recursion stack.
- Amortized O(1): a doubling array copies fewer than 2n elements over n appends.
- Read the input limits first: n = 10⁵ rules out O(n²) and points to O(n log n).
Check yourself
Answer to mark it learned; your answers aren't scored.
The interviewer says n ≤ 10⁵ with a ~1 s limit. Your first idea compares every pair of elements. What do you do?
Go deeper
Full explanation
Big-O is an upper bound on how cost grows with input size n, dropping constants and lower-order terms: 3n² + 10n is O(n²). In interviews it means the worst case unless you say otherwise.
How to derive it: sequential steps add (keep the biggest), nested loops multiply, halving the search space each step gives log n, and recursion costs calls × work per call. Count space too: the extra memory you allocate, including the recursion stack.
Amortized cost averages over a sequence: a dynamic array that doubles when full copies 1 + 2 + 4 + … < 2n elements in total, so append is O(1) amortized even though one append can be O(n).
Use it to choose before coding. At some hundreds of millions of simple operations per second, n = 10⁵ rules out O(n²) (10¹⁰ steps, tens of seconds) and asks for O(n log n). State it with variables you defined: O(V + E), O(n·k), not just "O(n)".
Code One problem, three complexities
# "Does the list contain a duplicate?" at three complexities.
def has_dup_pairs(a: list[int]) -> bool:
# O(n^2) time, O(1) extra space: compare every pair
for i in range(len(a)):
for j in range(i + 1, len(a)):
if a[i] == a[j]:
return True
return False
def has_dup_sort(a: list[int]) -> bool:
# O(n log n) time, O(n) space for the sorted copy: duplicates become neighbors
b = sorted(a)
return any(b[i] == b[i + 1] for i in range(len(b) - 1))
def has_dup_set(a: list[int]) -> bool:
# O(n) average time, O(n) space: trade memory for one pass
seen = set()
for x in a:
if x in seen: # O(1) average on a set; O(n) on a list
return True
seen.add(x)
return FalseReal example
Pair with a given sum, n = 10⁵. Checking every pair is n²/2 ≈ 5×10⁹ comparisons: tens of seconds. Sorting, then walking Two pointers inward, is O(n log n) time. One Hash maps, sets and prefix sums pass is O(n) time but O(n) extra space. Say it like this: "O(n) time and O(n) space, where n is the array length; I trade memory for a single pass."
Trade-offs +3 · −2
+ You gain
- Predicts whether an approach fits the limits before you write it.
- Independent of language and hardware: compares algorithms, not machines.
- A shared vocabulary to state the time-versus-space trade-off in one line.
− You pay
- Hides constants: an O(n) with a big constant can lose to O(n log n) at real sizes.
- Ignores the memory hierarchy: cache misses and allocations can dominate.
Use it when
Before coding any interview problem, and when choosing data structures for production paths whose inputs are large or growing.
Avoid it when
As the only argument at small, fixed n, where constants dominate: benchmark instead. A simple O(n²) over 50 items is fine.
Numbers to know 4
- ~1 s budget (CPH): n ≤ 20 → O(2ⁿ); n ≤ 500 → O(n³); n ≤ 5,000 → O(n²); n ≤ 10⁶ → O(n log n) or O(n).
- A modern CPU runs some hundreds of millions of simple operations per second; O(n²) at n = 10⁵ is 10¹⁰ steps.
- log₂(10⁶) ≈ 20 and log₂(10⁹) ≈ 30: a log factor is cheap.
- Python:
x in listandlist.pop(0)are O(n);x in setis O(1) average anddeque.popleft()is O(1).
Common pitfalls 4
- Not defining n: with two inputs, say O(n + m) or O(n·m), not just O(n).
- Hidden linear work inside a loop:
x in list,list.pop(0)or slicing turn O(n) into O(n²). - Forgetting the recursion stack: depth-n recursion uses O(n) space even with no data structures.
- Quoting the average as the worst case: hash lookups are O(1) average, O(n) worst.
Interview questions 3
Answer out loud first, then reveal.
How do you state the complexity of your solution?Show answer
I define the variables, then give time and space separately: "O(n log n) time, dominated by the sort, and O(n) extra space for the map, where n is the number of events." I say whether it's worst case, average or amortized. If there's a trade-off I name it unprompted: "I could drop the map and save memory, but each lookup would become a binary search."
Why is append O(1) if resizing copies the whole array?Show answer
Because it's amortized. When full, the array allocates a buffer twice as big and copies everything. Over n appends the copies sum to 1 + 2 + 4 + … < 2n, so the total is O(n) and each append is O(1) on average. Any constant growth factor above 1 works; growing by a fixed 10 slots instead would make n appends cost O(n²).
Your O(n) solution benchmarks slower than an O(n log n) one. How?Show answer
Big-O hides constants and memory effects. At n = 10⁶, log n is only ~20, so a 20× constant difference flips the ranking. A hash map pays for hashing, pointer chasing and cache misses on every operation; sorting a contiguous array streams through memory. I'd profile at our real n and decide on measured time, keeping Big-O as the guard against growth.