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

02000400020004000ncount
Measured
Table
ncount
89
1617
3233
6465
128129
256257
512513
10241,025
20482,049
40964,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
  1. Each call handles one element and makes one recursive call: n + 1 calls including the base case.
  2. Each call does O(1) work: Θ(n) time.
  3. 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.