Skip to content

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.

15 min read0/6 questions

"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.

How the common costs grow
input size n →ops
  • O(1)1
  • O(log n)4
  • O(n)16
  • O(n log n)64
  • O(n²)256
ShapeTypical costSay it as
One loop over n items, O(1) work eachO(n)"one pass"
Loop that halves the range each stepO(log n)"halves each time"
Sort, then one passO(n log n)"dominated by the sort"
Loop inside a loop, both over nO(n²)"every pair"
Try every subsetO(2ⁿ)"two choices per element"

The trap is hidden loops: a single line that secretly walks the whole input.

Quick check
What is the time complexity of this function?
def has_dupe(nums):
  seen = []
  for x in nums:
      if x in seen:
          return True
      seen.append(x)
  return False
Need a nudge? A hint rules out a wrong answer.

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.

Predict the outputPython

What does this print?

n = 8
i = 1
steps = 0
while i < n:
  i *= 2
  steps += 1
print(steps)
Need a nudge? Hints walk you through it.

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.

Pythonamortized.py
nums = [3, 1, 4, 1, 5, 9, 2, 6]stack, pushes, pops = [], 0, 0for x in nums: while stack and stack[-1] < x: stack.pop() pops += 1 stack.append(x) pushes += 1print("pushes:", pushes, "pops:", pops, "left:", len(stack))print("pops never exceed pushes:", pops <= pushes)
Output
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)).

Predict the outputPython

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))
Need a nudge? Hints walk you through it.

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.

Predict the outputPython

What does this print?

def depth(n):
  if n == 0:
      return 1
  return 1 + depth(n // 2)

print(depth(16))
Need a nudge? Hints walk you through it.
Quick check
A recursive DFS visits every node of a binary tree with n nodes. What is the extra space?
Need a nudge? A hint rules out a wrong answer.

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 SumTimeExtra spaceNote
Check every pairO(n²)O(1)Simple, too slow for 10^4 or more
Sort, then two pointersO(n log n)O(n)Must carry indices through the sort
Hash map, one passO(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 the pairs0/5 matched

Match each description to its time complexity.

Choose an item, then its match on the other side.

To drill this, open the Decoder and stop at the target-complexity stage. Say your target and why before you reveal the model answer.

ChallengeMedium

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^4
  • 1 <= k <= the number of distinct values.
  • The answer is unique: there is no tie at the cut-off.
def top_k_frequent(nums: list[int], k: int) -> list[int]: # Count first, then pick the k most common values. pass
ChallengeEasy

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]        →  true

Constraints

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
def contains_duplicate(nums: list[int]) -> bool: # Remember what you have already seen. pass
Key terms
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, or pop(0).
lower bound
The least work any solution must do, such as reading every element once: O(n).