Lesson 3: Analysing Loops, Recursion and Space
Knowing the vocabulary of Big-O is one thing; applying it to code you have never seen before is another. The skill is a matter of counting how many times the basic operations run, and the patterns repeat. A single loop over n items is O(n). Two nested loops are O(n^2). A loop that halves its range each time — such as while n > 1: n //= 2 — is O(log n). And a loop whose body does an O(n) operation, such as searching a list with in, costs O(n) per iteration, so the whole loop is O(n^2) — a classic hidden cost that catches many beginners.
Recursion needs a different tool: a recurrence, an equation describing the work in terms of smaller inputs. A recursive function that halves its input and does constant work is T(n) = T(n/2) + O(1), which solves to O(log n) — that is binary search again. A function that makes two recursive calls on half the input, like merge sort, gives T(n) = 2T(n/2) + O(n), which solves to O(n log n). And the naive recursive Fibonacci, which calls itself twice on inputs only one smaller, gives T(n) = T(n-1) + T(n-2), which grows exponentially — roughly O(2^n). That is why the naive Fibonacci is unusable past small numbers, and why the next unit's dynamic programming matters so much.
# Count the work: which of these is secretly O(n^2)?
nums = list(range(1000))
total = 0
for x in nums: # O(n): one pass
total += x
pairs = 0
for a in nums: # O(n^2): nested loops
for b in nums:
if a < b:
pairs += 1
# Hidden cost: `x in nums` is itself O(n), so this loop is O(n^2)
seen = []
for x in nums:
if x not in seen:
seen.append(x)
Space complexity, and the time-memory trade-off
Time is only half the story. Space complexity describes how much extra memory an algorithm uses as the input grows. An algorithm that sorts in place uses O(1) extra space; one that builds a copy of the input uses O(n). Recursion uses space too: each call adds a frame to the call stack, so a recursive function that goes n calls deep uses O(n) stack space — and Python has a default recursion limit (usually 1,000 frames), which deep recursion can hit. In contests, the memory limit is usually generous, but an algorithm that stores every pair of items — O(n^2) space — will run out of memory long before it runs out of time.
Time and memory are often traded against each other. The classic example is memoisation: storing the answers to subproblems you have already solved costs memory, but saves you from recomputing them, turning an exponential algorithm into a fast one. That trade is the heart of dynamic programming, which you will meet in Unit 3. For now, the habit to build is asking both questions about every algorithm you write: how does the time grow, and how does the memory grow?
Going further
Recurrences like T(n) = 2T(n/2) + O(n) can be solved systematically with the Master theorem, a recipe that covers most divide-and-conquer recurrences. It compares the work done at each level with the number of subproblems: if the work per level stays the same, the total is O(n log n); if it shrinks, the top level dominates; if it grows, the leaves dominate. You do not need the theorem's formal statement to use it — the intuition is enough for now — but knowing it exists means you can look it up whenever a new recurrence appears, instead of deriving the answer from scratch.
There is one more kind of analysis worth knowing by name: amortised analysis. Appending to a Python list is O(1) most of the time, but occasionally the list must grow, which costs O(n) to copy everything. Looked at one operation at a time, the worst case is linear; looked at over a long sequence of appends, the average cost per append is constant, because the expensive resizes are rare. That average-over-a-sequence is the amortised cost, and it is the honest way to describe operations whose cost varies — including the dynamic arrays and hash tables you use every day.
A classic hidden cost is worth a closer look: building a string by repeated concatenation with result = result + piece inside a loop. Because strings are immutable in Python, each step creates a new string holding everything built so far, so a loop that adds a thousand pieces does roughly a thousand times a thousand characters of copying — quadratic work hiding behind an innocent-looking line. The standard fix is to collect the pieces in a list and join them once at the end with "".join(pieces), which is linear. It is the same lesson as the membership test: know what your operations cost, especially the ones inside a loop.
Key Terms
- Recurrence
- An equation describing an algorithm's running time in terms of the time for smaller inputs.
- Space complexity
- How much extra memory an algorithm uses as the input size grows.
- Call stack
- The stack of function-call frames; each recursive call adds one frame.
- Hidden cost
- An operation that looks cheap but is itself O(n), such as x in list inside a loop.
- O(n log n)
- The complexity of efficient comparison sorts such as merge sort and quick sort.
- Exponential time O(2^n)
- Running time that doubles with each extra input item; unusable beyond small inputs.
- Time-memory trade-off
- Using extra memory (such as stored answers) to save time, or vice versa.
Discussion Questions
- Why is x in list inside a loop so expensive? What data structure would you use instead if you only need membership tests?
- The naive recursive Fibonacci is O(2^n). Trace it for n = 5 and count how many times fib(2) is computed. What does that tell you?
- When would you accept O(n) extra space to make an algorithm faster? When would you refuse?
Practice Questions
- A loop runs n times and does O(1) work each time. What is the total complexity?
- What is the recurrence for binary search, and what does it solve to?
- Why does deep recursion risk crashing in Python?
- Sorting in place uses O(1) extra space; building a sorted copy uses O(n). Which is which, and why?
- An algorithm stores the answer to every subproblem it solves. What is it trading, and for what?
Show answers
- O(n). n iterations times constant work per iteration.
- T(n) = T(n/2) + O(1), which is O(log n). Each step halves the input and does constant work.
- Each call adds a frame to the call stack, and Python limits the stack depth (usually 1,000 frames). A recursion n calls deep uses O(n) stack space.
- In-place sorting reuses the input's memory; a copy allocates a new list of size n. Space complexity counts extra memory beyond the input itself.
- It trades memory for time. Storing answers costs O(number of subproblems) space but avoids recomputing them — the memoisation idea.