Exercise 14 of 30 · beginner · recursion · call stack · linear
Recursion that peels off one element
The code
def total(items, i=0):
if i == len(items):
return 0
return items[i] + total(items, i + 1)What are the time and the extra space?
Count: calls.
Measured counts
Table
| n | count |
|---|---|
| 8 | 9 |
| 16 | 17 |
| 32 | 33 |
| 64 | 65 |
| 128 | 129 |
| 256 | 257 |
| 512 | 513 |
| 1024 | 1,025 |
| 2048 | 2,049 |
| 4096 | 4,097 |
Try to name the class from the shape before opening the answer.
Show the answer and derivation
- Time
- Θ(n)
- Extra space
- Θ(n) call stack
- Exact count
- n + 1 calls
- Each call handles one element and makes one recursive call: n + 1 calls including the base case.
- Each call does O(1) work: Θ(n) time.
- All n + 1 frames are on the stack at the deepest point: Θ(n) space (and a stack overflow risk for large n).
Common mistake: Calling the space O(1) because no data structure is allocated. The call stack is memory.
Check: measured count ÷ (n) settles near 1.00 for large n.