Time & Space Complexity
Estimate how work and memory grow with input size before you write a line.
- active this step
- visited / done
- result
Create an empty set
seen will grow to at most n items, so this solution uses O(n) extra memory.
VARIABLES
- x
- -
- seen
- set()
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
Big-O describes how running time or memory grows as the input size n grows, ignoring constant factors.
Why it matters
It lets you compare solutions, and constraints like n ≤ 10⁵ tell you which complexities will pass.
Think of it like this
Reading every page to find a word is O(n); jumping to the index at the back is closer to O(log n).
Use it when
- Choosing between two working solutions
- Reading constraints to rule out brute force
- Explaining time vs memory trade-offs
Avoid it when
- Treating Big-O as exact runtime - constants still matter for small n
- Ignoring hidden costs like slicing or string += inside loops
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Loop over n items | O(n) | O(1) |
| Nested loop over all pairs | O(n²) | O(1) |
| Sort, then scan | O(n log n) | O(n) |
Often confused with: average vs worst case - dict lookups are O(1) on average but O(n) in the worst case.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- About 10⁸ simple operations per second is a common rule of thumb
- n ≤ 20 often allows O(2ⁿ); n ≤ 10⁵ needs O(n log n) or better
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Calling a nested loop O(n) because the inner loop “looks small”
- Forgetting that slicing (nums[1:]) or string += in a loop copies data
- Leaving out the space used by recursion depth or extra sets
Edge cases to test
- Empty input - make sure the return value is still right
- All elements equal - the worst case for some algorithms
- Very large n - recursion can hit Python’s default limit of 1000 frames
Knowledge check
Quick check to lock in the intuition.
A loop starts at i = 1 and doubles i until i ≥ n. What is its time complexity?
Practice
Apply what you just watched on real interview problems.