Problem Solving — CS & DS

Lecture 22 — Recursion and Divide-and-Conquer

Learning objectives

Case-based lecture: you attempt, we discuss, then we reveal.

Today

The plan

Key definitions

Key definitions

Explain each in one breath; the cases will do the heavy lifting.
Worked example

Digit Sum, Twice: recursion as self-similar bookkeeping

cs-086

Compute the digit sum of 49206 - recursively, then with iteration. Both must print the same number.

def dsum(n):
    if n < 10:
        return n
    return n % 10 + dsum(n // 10)

def dsum_iter(n):
    total = 0
    while n > 0:
        total += n % 10
        n //= 10
    return total

print(dsum(49206), dsum_iter(49206), dsum(0))

Expected: 21, 21, and 0 for the empty case

Cost: O(digits) either way; recursion adds stack frames, iteration a variable.

Worked example

Power by Halving: divide-and-conquer in one line

cs-087

Compute 3^13 by repeated squaring, not by twelve multiplications.

def power(x, e):
    if e == 0:
        return 1
    h = power(x, e // 2)
    if e % 2 == 0:
        return h * h
    return x * h * h

print(power(3, 13), 3 ** 13)

Expected: 1594323 (matches the built-in power)

Cost: O(log e) multiplications; big integers make each multiply slower as values grow, but the count is the point.

Worked example

The Tower Steps: recursion that repeats itself

cs-088

Staircase of 8 steps; you climb 1 or 2 at a time. How many distinct ways to the top?

calls = {"plain": 0, "memo": 0}

def ways_plain(n):
    calls["plain"] += 1
    if n <= 2:
        return n
    return ways_plain(n - 1) + ways_plain(n - 2)

def ways_memo(n, cache={1: 1, 2: 2}):
    calls["memo"] += 1
    if n in cache:
        return cache[n]
    cache[n] = ways_memo(n - 1) + ways_memo(n - 2)
    return cache[n]

print(ways_plain(8), ways_memo(8), calls["plain"], calls["memo"])

Expected: 34 ways; plain recursion made 67 calls, memoised 15

Cost: Plain: O(2^n)-ish (golden-ratio precise). Memoised: O(n) time and space - this is dynamic programming arriving by fix-it ticket, formally next lecture.

Case attempt · lecture 22
Case cs-085 · Beginner

The Russian Dolls

Describe nested dolls recursively; write the function that counts layers. Base case and trust in the recursive call, made concrete.

⏱ 5 minutes — attempt now

Pseudocode, flowchart or Python. State one assumption. Compare with your neighbour at minute 4.

Discussion

cs-085 — discuss

Instructor: the reveal, the reasoning section and common wrong turns are in the instructor distribution for cs-085 — not embedded in this deck.

Case attempt · lecture 22
Case cs-086 · Foundational

Digit Sum, Twice

Digit sum via loop vs recursion; then count the calls. Same result, different shapes; when recursion mirrors the problem's structure.

⏱ 5 minutes — attempt now

Pseudocode, flowchart or Python. State one assumption. Compare with your neighbour at minute 4.

Discussion

cs-086 — discuss

Instructor: the reveal, the reasoning section and common wrong turns are in the instructor distribution for cs-086 — not embedded in this deck.

Case attempt · lecture 22
Case cs-087 · Intermediate

Power by Halving

Compute x^n with O(log n) multiplications by halving the exponent. Divide-conquer-combine, with a trace that shows the saving.

⏱ 5 minutes — attempt now

Pseudocode, flowchart or Python. State one assumption. Compare with your neighbour at minute 4.

Discussion

cs-087 — discuss

Instructor: the reveal, the reasoning section and common wrong turns are in the instructor distribution for cs-087 — not embedded in this deck.

Case attempt · lecture 22
Case cs-088 · Expert

The Tower Steps

Count ways to climb n steps taking 1 or 2 at a time. Recursion tree shows re-computation; memoisation saves it. The bridge to dynamic programming.

⏱ 5 minutes — attempt now

Pseudocode, flowchart or Python. State one assumption. Compare with your neighbour at minute 4.

Discussion

cs-088 — discuss

Instructor: the reveal, the reasoning section and common wrong turns are in the instructor distribution for cs-088 — not embedded in this deck.

Check yourself

Common misconceptions

Summary

Summary & exit question

Exit question (choose one, 60 seconds)

  1. What grounds a recursion?
  2. When does a table beat the tree?
  3. What did cs-087 buy with halving?
Expected answers (instructor): a base case reachable for every input path when subproblems repeat — overlapping subproblems multiplications dropped from ~13 to ~5 — logarithmic vs linear
→ / space: next · ←: back · Home/End: jump · Ctrl+P → PDF