Python 3D Academyবাংলা

Reading the cost of a recursion: level by level

🌍 In real life. At an exam centre, 8 answer scripts arrive in one pile. The head examiner checks the cover page of every script in the pile, then hands half to each of two assistants. Each assistant checks every cover page in their half and passes half of it on to two more helpers, and so on, until everyone holds a single script. How many cover-page checks in all?

You could follow every person, but there is a quicker way: count one layer of people at a time. The head examiner checks 8. The two assistants check 4 + 4 = 8. The four helpers check 2 + 2 + 2 + 2 = 8. Every layer checks the whole pile once, and the pile halves 3 times before it is single scripts: 4 layers × 8 = 32.

The idea in one sentence: to find a recursion's cost, draw its tree, write beside each call the work it does itself (not counting its calls), add the work up level by level, and multiply by the number of levels.

Its words:

  • level: all the calls at the same depth of the tree
  • height: how many levels there are; when the size halves each time, about log₂ n + 1

Step by step:

  1. How many calls does each call make, and on how much smaller a problem?
  2. How much work does one call do itself?
  3. Add up the work on one level
  4. Count the levels, and multiply (or add, if the levels differ)

Here every call does work on all its items, then splits them into two halves:

When n is not a power of 2, the halves are uneven (5 splits into 2 and 3) and the bottom level is not full, but no level does more than n work:

Why it is correct. Every call sits on exactly one level, so adding the level totals counts every call's own work exactly once: nothing missed, nothing twice.

What it costs: the shapes to recognise. Most recursions in this course have one of these trees:

  • one call, one smaller, constant work (a sum going one item at a time): n levels × 1 = O(n)
  • one call, half the size, constant work (fast_power, binary search in Chapter 43): log₂ n levels × 1 = O(log n)
  • two calls, half the size, constant work (the knockout cup): the levels hold 1, 2, 4, … n calls, which add up to about 2n = O(n)
  • two calls, half the size, linear work (the scene above, and merge sort in Chapter 45): log₂ n + 1 levels × n = O(n log n)
  • two calls, one smaller (plain fib): each level can have twice the calls of the one above = O(2ⁿ) at most (about 1.6ⁿ for fib)

So it is not the number of calls per call that decides the cost, but how fast the size shrinks together with how much work each level does. For 1024 items that is 1024 × 11 = 11,264 steps (n log₂ n alone is 10,240); n² would be over a million.

def halvings(n):                  # one call, half the size: log n
    if n == 1:
        return 0
    return 1 + halvings(n // 2)

def split_work(n):                # two calls, half the size, n work: n log n
    if n == 1:
        return 1
    return n + split_work(n // 2) + split_work(n - n // 2)

for n in [8, 1000, 10 ** 6]:
    print(n, halvings(n))
for n in [8, 5, 1000]:
    print(n, split_work(n), n * (halvings(n) + 1))  # equal only when n is a power of 2

Mistakes and edge cases.

  • forgetting a call's own work: the cost is the work at every node, not just the number of leaves
  • n / 2 instead of n // 2: / gives floats (3 / 2 is 1.5), which halve forever without reaching 1 exactly; the base case is never met and you get a RecursionError
  • "two calls means 2ⁿ": only when the size shrinks by one. Two calls on halves is O(n) or O(n log n), depending on the work per level
  • uneven halves: with n // 2 and n - n // 2 the parts differ by at most one, so there are still about log₂ n + 1 levels

Quiz

  1. f(n) returns 1 when n <= 1, and f(n // 2) + 1 otherwise. What is its Big-O?

    • O(log n): one call, half the size, constant work
    • O(n)
    • O(n log n)
  2. g(n) returns 1 when n <= 1, and g(n - 1) + g(n - 1) otherwise. What is its Big-O?

    • O(2ⁿ): two calls, each only one smaller
    • O(n): two calls is still linear
    • O(n log n)
  3. What does this print?

    work = [0, 0, 0]
    
    def solve(n, depth=0):
        work[depth] += n
        if n > 1:
            solve(n // 2, depth + 1)
            solve(n // 2, depth + 1)
    
    solve(4)
    print(work)
  4. A problem of size 32 halves at every level until the parts have size 1. How many levels are there, counting the top?

    • 6
    • 5
    • 32
  5. halvings(6) stops with a RecursionError instead of giving 2. Which line is wrong?

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

Coding tasks

  1. Write a recursive halvings(n): how many times a whole number n ≥ 1 can be halved with // 2 before it reaches 1. halvings(8) is 3 and halvings(9) is 3. This is the height of a halving recursion, minus the top.

  2. A recursion does n steps of work on n items, then splits them into halves of n // 2 and n - n // 2 and does the same to each, until a part has one item (which costs 1). Write a recursive split_work(n): the total steps. split_work(8) is 32 and split_work(5) is 17.