Skip to content

Lesson 2 of 40Foundations

Analyzing Code

Read a piece of code and work out its time and space complexity, including loops, recursion and hidden costs.

18 min read0/8 questions

Knowing the names of the complexities is half the job. The other half is looking at real code and saying "that is O(n log n)" with confidence. Interviewers ask "what is the complexity of this?" about every solution you write, and the answer has to come from reading the code, not from memory.

You only need a handful of rules. This lesson covers them one at a time.

Rule 1: sequential blocks add

Code that runs one block after another adds its costs. Then you keep the biggest term.

def stats(nums):
    total = sum(nums)          # O(n)
    nums_sorted = sorted(nums) # O(n log n)
    return total, nums_sorted[0]  # O(1)

O(n) + O(n log n) + O(1) = O(n log n). The sort dominates.

Rule 2: nested loops multiply

A loop inside a loop multiplies. If the outer loop runs n times and the inner loop runs n times for each of those, the body runs n × n times.

Python
def count_pairs(nums): steps = 0 for i in range(len(nums)): for j in range(i + 1, len(nums)): steps += 1 return steps for n in [10, 20, 40]: print(n, "->", count_pairs(list(range(n))))
Output
Press Run (⌘ Enter) to see what happens.

Notice the inner loop starts at i + 1, so it does n − 1, then n − 2, and so on. The total is about n²/2, which is still O(n²): double the input and the work goes up four times, which is what the output shows (45, 190, 780).

Quick check
What is the time complexity?
def has_common(a, b):
  for x in a:
      for y in b:
          if x == y:
              return True
  return False
Need a nudge? A hint rules out a wrong answer.
Quick check
What is the time complexity?
def two_loops(nums):
  for x in nums:
      print(x)
  for x in nums:
      print(x * 2)
Need a nudge? A hint rules out a wrong answer.

Rule 3: halving is log n

When each step cuts the remaining work in half, the number of steps is log₂ n.

Python
def halvings(n): steps = 0 while n > 1: n //= 2 steps += 1 return steps for n in [8, 1024, 1_000_000]: print(n, "->", halvings(n), "steps")
Output
Press Run (⌘ Enter) to see what happens.

A million shrinks to 1 in 19 steps. The same is true when a loop variable doubles (i *= 2) up to n. If you see the work shrinking by a constant factor each time, think log n.

Quick check
What is the time complexity?
def f(n):
  for i in range(n):
      j = 1
      while j < n:
          j *= 2
Need a nudge? A hint rules out a wrong answer.

Rule 4: recursion, draw the tree

For a recursive function, ask two questions: how many calls happen in total, and how much work each call does on its own. Drawing the call tree answers the first.

Python
def fib(n): if n <= 1: return n return fib(n - 1) + fib(n - 2) print([fib(i) for i in range(10)])
Output
Press Run (⌘ Enter) to see what happens.
Calls made by fib(4)
fib(4)fib(1)fib(0)fib(2)fib(1)fib(3)fib(1)fib(0)fib(2)root

One call at the top. Each call that is not a base case makes two more calls.

1/4

A useful shortcut: branches ^ depth. A function that calls itself twice and goes n levels deep is O(2ⁿ). A function that calls itself once on n - 1 (like a recursive sum) is a straight line of n calls: O(n).

Divide and conquer, and the Master Theorem intuition

Merge sort splits the list in half, sorts each half recursively, then merges them in O(n). Draw the tree: the top level does n work (one merge of n items), the next level does two merges of n/2 (still n total), the next does four merges of n/4 (still n). Every level costs n, and halving gives log n levels, so the total is O(n log n).

The Master Theorem formalises this for recurrences like T(n) = a·T(n/b) + f(n). The intuition is a tug of war between the work at the top and the number of leaves at the bottom:

  • If each level does the same total work (merge sort), multiply by the number of levels: O(n log n).
  • If the work shrinks going down (one call on half the input plus O(n) work), the top level dominates: O(n).
  • If the number of calls grows faster than the work shrinks, the leaves dominate.

Binary search is T(n) = T(n/2) + O(1): one call on half, constant work, so O(log n).

Quick check
What is the time complexity?
def power_set(items):
  if not items:
      return [[]]
  rest = power_set(items[1:])
  return rest + [[items[0]] + r for r in rest]
Need a nudge? A hint rules out a wrong answer.

Amortized cost: why append is O(1)

A Python list or JS array sits in one block of memory with some spare room (its capacity). When it is full, append allocates a block twice as big and copies everything over. That copy is O(n). So how can append be O(1)?

A dynamic array that doubles
7
0
size = 1capacity = 1copies = 0

Capacity 1, holding one item.

1/6

The copies add up to 1 + 2 + 4 + ... + n, which is less than 2n. Spread across n appends, each one costs O(1) on average. This is called amortized O(1): any single append might be slow, but a long run of them averages out to constant time.

Hidden costs

Some one-liners hide a loop. These are the ones that catch people out.

CodeLooks likeActually
x in my_listO(1)O(n), scans the list
x in my_set / x in my_dictO(1)O(1) on average
nums[a:b] (slice)O(1)O(b − a), copies
my_list.insert(0, x) / pop(0)O(1)O(n), shifts everything
arr.shift() / arr.unshift(x) in JSO(1)O(n)
s += "x" in a loopO(n) totalcan be O(n²), strings are immutable
sorted(nums) / arr.sort()O(n)O(n log n)
arr.includes(x) / indexOf in JSO(1)O(n)

Strings in both Python and JS are immutable, so += can create a new string each time and copy all previous characters. Build a list of parts and "".join(parts) (Python) or parts.join("") (JS) instead.

Quick check
What is the time complexity?
def dedupe(nums):
  result = []
  for x in nums:
      if x not in result:
          result.append(x)
  return result
Need a nudge? A hint rules out a wrong answer.
Quick check
What is the time complexity?
def total(nums):
  if not nums:
      return 0
  return nums[0] + total(nums[1:])
Need a nudge? A hint rules out a wrong answer.
Predict the outputPython

How many times does this loop run?

n = 64
count = 0
while n > 1:
  n = n // 2
  count += 1
print(count)
Need a nudge? Hints walk you through it.

Space: count what you keep, including the call stack

Space complexity counts extra memory: new lists, sets, dicts, and also recursion depth. Each recursive call that has not returned yet holds a frame on the call stack.

Python
def sum_recursive(nums, i=0): if i == len(nums): return 0 return nums[i] + sum_recursive(nums, i + 1) # n frames deep: O(n) space def sum_loop(nums): total = 0 for x in nums: # one variable: O(1) space total += x return total print(sum_recursive([1, 2, 3, 4]), sum_loop([1, 2, 3, 4]))
Output
Press Run (⌘ Enter) to see what happens.

Python's default recursion limit is about 1,000 frames, so a recursive solution on 100,000 items will crash with RecursionError. In space terms, recursion depth d costs O(d). For fib, the tree has 2ⁿ calls but is only n deep at any moment, so it uses O(n) space.

Put it in order5 steps

Put these steps for analysing a function in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
ChallengeEasy

Common elements

Given two lists of integers a and b, return the values that appear in both, each value once, sorted ascending.

a = [4, 1, 3, 1], b = [3, 4, 9]  →  [3, 4]
a = [1, 2], b = [5]              →  []

The obvious solution checks x in b for every x in a. On lists, in is O(m), so that is O(n·m). Get it down to O(n + m) for the matching step (the final sort of the answer is fine).

def common_elements(a: list[int], b: list[int]) -> list[int]: # Hint: membership checks on a set are O(1) on average. pass
Key terms
nested loops multiply
A loop of size a inside a loop of size b runs its body a · b times.
sequential blocks add
Blocks that run one after another add their costs; keep the biggest term.
recursion tree
A drawing of every call a recursive function makes. Total time = number of calls × work per call.
amortized O(1)
Averaged over many operations, each one costs O(1), even if an occasional one is expensive (like a dynamic array resize).
hidden cost
A one-liner that loops internally, such as in on a list, slicing, or sort.
call stack space
Each unfinished recursive call holds memory. Depth d costs O(d) space.