Exercise 16 of 30 · intermediate · recursion · logarithmic · recurrences

Recursion on half the input

The code

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

Solve T(n) = T(n/2) + O(1).

Count: calls.

Measured counts

051020004000ncount
Measured
Table
ncount
84
165
326
647
1288
2569
51210
102411
204812
409613

Try to name the class from the shape before opening the answer.

Show the answer and derivation
Time
Θ(log n)
Extra space
Θ(log n) stack
Exact count
⌊log₂ n⌋ + 1 calls
  1. Each call halves n and does constant work.
  2. The recursion bottoms out after ⌊log₂ n⌋ halvings.
  3. Binary search written recursively has exactly this shape.

Common mistake: Forgetting the stack: the iterative version is O(1) space, the recursive one Θ(log n).

Check: measured count ÷ (log n) settles near 1.08 for large n.