Lesson 16 of 27Talk it through
Explaining Complexity
State time and space out loud with a reason, including amortized costs, recursion stacks, and trade-offs.
"What is the time and space complexity?" comes up in almost every coding interview, usually right after your code runs. A bare "O(n)" is a weak answer. A strong one names the variable, gives the reason, and mentions the space you used, in about two sentences.
This lesson is about saying it well: how to count, how to justify, and how to compare your approach with the alternatives.
The two-sentence formula
Use this shape every time:
"This is O(…) time because … It uses O(…) extra space for …"
For Two Sum with a hash map: "This is O(n) time, where n is the length of nums, because I visit each element once and each map lookup is O(1) on average. It uses O(n) extra space for the map, which can hold up to n entries."
Three details make that answer strong:
- Name the variables. If there are two inputs, say which is which: "O(n · m) where n is the number of rows and m the number of columns."
- Give the reason. The reason is what the interviewer is checking. It shows you counted rather than guessed.
- Separate output from extra space. The list you must return is usually not counted as extra space. Say so: "O(1) extra space, not counting the output array."
How to count
Analyzing Code in the Algorithms & Patterns course teaches the counting rules in full. Here is the short version you say out loud. Count how many times the innermost work runs, and how much each run costs. Most code falls into a few shapes.
| Shape | Typical cost | Say it as |
|---|---|---|
| One loop over n items, O(1) work each | O(n) | "one pass" |
| Loop that halves the range each step | O(log n) | "halves each time" |
| Sort, then one pass | O(n log n) | "dominated by the sort" |
| Loop inside a loop, both over n | O(n²) | "every pair" |
| Try every subset | O(2ⁿ) | "two choices per element" |
The trap is hidden loops: a single line that secretly walks the whole input.
Other common hidden costs: slicing (nums[1:] copies), list.pop(0) and JavaScript shift() (both shift every element), sorted() or .sort() inside a loop, str.join inside a loop, and arr.includes or indexOf in JavaScript.
What does this print?
n = 8 i = 1 steps = 0 while i < n: i *= 2 steps += 1 print(steps)
Amortized cost
Some code has an inner loop that looks like it makes the whole thing O(n²), but does not. The trick is to count the total work across the whole run instead of the worst case of one iteration. That is called amortized analysis.
The classic example is a monotonic stack. Each element is pushed once and popped at most once, so all the pops together are at most n, no matter how they are spread out.
Press Run (⌘ Enter) to see what happens.Some iterations pop several items, many pop none. Added up, pops plus what is left on the stack equals the number of pushes. So the whole loop is O(n).
Say it like this: "The inner while looks nested, but each element is pushed once and popped at most once, so the total work across all iterations is O(n). It is amortized O(1) per element."
The same argument covers sliding windows (each index enters and leaves once) and appending to a Python list or JavaScript array (an occasional resize copies everything, but it happens rarely enough that each append is amortized O(1)).
What does this print?
nums = [3, 1, 4, 1, 5]
stack, pops = [], 0
for x in nums:
while stack and stack[-1] < x:
stack.pop()
pops += 1
stack.append(x)
print(pops, len(stack))Space, including the recursion stack
Extra space is everything you allocate beyond the input: maps, sets, copies, queues, and the call stack. Each recursive call that has not returned yet holds a stack frame, so recursion depth is space.
- DFS on a balanced binary tree: depth is about log n, so O(log n) stack space.
- DFS on a skewed tree (a straight line): depth is n, so O(n). Say "O(h) where h is the height, which is O(n) in the worst case."
- Memoized recursion: the memo table plus the stack depth.
Python's default recursion limit is 1000 frames, so a recursive DFS on a 10^5-node path will crash. Mentioning that, and offering an iterative version with an explicit stack, is a strong signal.
What does this print?
def depth(n):
if n == 0:
return 1
return 1 + depth(n // 2)
print(depth(16))Comparing alternatives
The best answers do not just describe your solution. They place it among the others. A small table in your head is enough:
| Approach for Two Sum | Time | Extra space | Note |
|---|---|---|---|
| Check every pair | O(n²) | O(1) | Simple, too slow for 10^4 or more |
| Sort, then two pointers | O(n log n) | O(n) | Must carry indices through the sort |
| Hash map, one pass | O(n) | O(n) | Trades memory for speed |
Then say the trade-off in one sentence: "I chose the hash map because time matters more than memory here. If memory were the constraint, the pair check uses O(1) space."
Two follow-ups often come next:
- "Can you do better?" Think about a lower bound. If you must look at every element, nothing beats O(n). "I have to read each number at least once, so O(n) is optimal."
- "What is the worst case for the hash map?" Average O(1) lookups can degrade with many collisions. It is rare in practice, and saying you know it is enough.
Match each description to its time complexity.
To drill this, open the Decoder and stop at the target-complexity stage. Say your target and why before you reveal the model answer.
Top K Frequent Elements
Given a list of integers nums and a number k, return the k values that appear most often. You can return them in any order. Aim for better than O(n log n).
nums = [1, 1, 1, 2, 2, 3], k = 2 → [1, 2]
nums = [4, 4, 4, 6, 6, 5], k = 1 → [4]
nums = [1], k = 1 → [1]Constraints
1 <= nums.length <= 10^5-10^4 <= nums[i] <= 10^41 <= k <=the number of distinct values.- The answer is unique: there is no tie at the cut-off.
Contains Duplicate
You are given a list of integers nums. Return true if any value shows up at least twice, and false if every value is distinct.
nums = [1, 2, 3, 1] → true (1 appears twice)
nums = [1, 2, 3, 4] → false
nums = [5, 5, 5] → trueConstraints
0 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
- extra space
- Memory you allocate beyond the input, usually not counting the output you must return.
- amortized
- The average cost per operation over a whole run, even if a few operations are expensive.
- call stack space
- Memory held by recursive calls that have not returned. Equal to the maximum recursion depth.
- hidden loop
- A single line that walks the input, like
x in list, slicing, orpop(0). - lower bound
- The least work any solution must do, such as reading every element once: O(n).