Lawfare Academy

CS 201 — Data Structures, Algorithms and Systems · Weeks 9–11

Recursion, trees and computational state

Full teaching sequence and cumulative subject work

Preparation: study 2.5 and 3.2: induction, strong induction and proof methods in the complete on-site Levin text. Attempt the investigation, work at least four exercises of increasing difficulty in each assigned section, and compare the selected hints/solutions only after a written attempt. Then complete the algorithm reading and implement the unit laboratory. For each algorithm give a specification, trace, correctness argument and time/space analysis.

Weighted shortest paths: implementation, proof and complexity — primary material, constructed-response tasks, complete worked model and changed-case examination →

Recurrences, memoization and proof obligations

A recurrence defines both its base cases and the relation among subproblems. For stair counts, ways(0)=1 represents the empty sequence; negative remaining distance contributes zero. This is a counting convention tied to the problem, not a universal rule that every recursive function returns one at zero.

Memoization removes repeated subproblem evaluation but not every resource cost. A recursive memoized function can retain a deep call stack. Bottom-up iteration can keep only the preceding two values for this recurrence. As values grow, arithmetic cost and integer storage can matter even when the number of recurrence steps is linear.

Worked problem

Count ordered sequences of one- and two-step moves covering five stairs. Compare naive recursion with a bottom-up state pair.

Trace the complete reasoning
  1. Starting with ways(0)=1 and ways(1)=1 gives ways(2)=2, ways(3)=3, ways(4)=5 and ways(5)=8.

  2. Naive recursion recomputes smaller states through multiple branches. Memoization evaluates each remaining-distance state once, while retaining cached results.

  3. An iterative pair holds the preceding two counts and updates them through five. Its invariant identifies those counts at the start of each iteration.

  4. The result counts orders separately: 1+2 and 2+1 are different sequences. An unordered partition problem would require a different recurrence.

Independent transfer problem

Moves may now be one or three stairs. State the recurrence and compute the count for five. Identify the required base convention.

Compare the transfer solution

Use f(n)=f(n−1)+f(n−3), f(0)=1 and f(n)=0 for n<0. The sequence for n=0 through 5 is 1,1,1,2,3,4. The four sequences for five are all ones and the three placements of one 3 among two 1s. Reusing the one-or-two recurrence would solve the wrong specification even if the memoization were perfect.

Learning objectives

  • Explain and trace the mechanisms in recursion, trees and computational state.
  • Apply the method to the worked example and changed-condition exercise.
  • Identify assumptions, failure cases and the evidence needed to justify a result.

Study the mechanism

Recursion solves a problem by invoking the same procedure on smaller cases. It needs a base case, a reduction toward that case and a way to combine results. A recursive call has its own local state; returning from it resumes the caller. Confusing caller and callee state is a common source of incorrect traces.

A binary tree can represent hierarchical structure, but not every binary tree is balanced and not every tree is a search tree. Search-tree ordering places smaller keys on one side and larger keys on the other under a defined duplicate policy. A chain-shaped tree can need linear lookup time. Balanced trees maintain additional invariants to limit height, paying maintenance costs on changes.

Memoization stores answers for repeated subproblems. It can turn exponential repeated work into linear or polynomial work when subproblems overlap, but consumes memory and requires an appropriate cache key. Caching a result that depends on hidden mutable state can return a stale answer. Dynamic programming is a problem-structure technique rather than a command to make every function recursive. For untrusted or very deep structures, an explicit stack can avoid runtime recursion limits.

Worked example

def ways(n, memo=None):
    if n < 0:
        return 0
    if memo is None:
        memo = {0: 1}
    if n not in memo:
        memo[n] = ways(n - 1, memo) + ways(n - 2, memo)
    return memo[n]

assert ways(4) == 5

The function counts ordered sequences of one-step and two-step moves that cover n steps. There is one way to cover zero steps: take no moves. Negative subproblems contribute zero. For four steps the counts build as 1, 1, 2, 3, 5. Memoization avoids recomputing each smaller n repeatedly. This code is for small instructional inputs; very large n needs an iterative design and consideration of integer size.

Check your understanding

Why must a memoization key capture every relevant input?

  1. Otherwise different subproblems can incorrectly share one cached result
  2. Because caches prove every result correct
  3. Because recursion always requires a cache
Answer and reasoning for every option

Correct: Otherwise different subproblems can incorrectly share one cached result A cache can only reuse results for equivalent subproblems.

Reconsider: Because caches prove every result correct Incorrect computations remain incorrect when cached.

Reconsider: Because recursion always requires a cache Many recursive algorithms have no repeated subproblems.

Transfer laboratory: A recursion tree with repeated work

Trace the naive recurrence T(n)=T(n−1)+T(n−2) for the ways problem. Explain how memoization changes repeated subproblems and why an iterative version can still use growing integer memory.

Work through the full solution

The naive recursion recomputes the same n values along many branches. Memoization stores one result per distinct n, reducing the number of computed states to a linear count. Rolling iteration retains two counts, but each integer’s bit length grows with n, so constant variable count is not constant bit storage. Also account for arithmetic cost on large integers.

Evidence of understanding

Distinguish state count, call count, variable count and bit complexity.

Complete on-site teaching readings

These are full attributed source sections, not previews. Read them alongside the original Academy explanation and code.

  1. 6 . Binary Trees · Pat Morin
  2. 6 . 1 BinaryTree: A Basic Binary Tree · Pat Morin
  3. 6 . 2 BinarySearchTree: An Unbalanced Binary Search Tree · Pat Morin
  4. 6 . 3 Discussion and Exercises · Pat Morin
  5. 7 . Random Binary Search Trees · Pat Morin
  6. 7 . 1 Random Binary Search Trees · Pat Morin
  7. 7 . 2 Treap: A Randomized Binary Search Tree · Pat Morin
  8. 7 . 3 Discussion and Exercises · Pat Morin
  9. 8 . Scapegoat Trees · Pat Morin
  10. 8 . 1 ScapegoatTree: A Binary Search Tree with Partial Rebuilding · Pat Morin
  11. 8 . 2 Discussion and Exercises · Pat Morin
  12. 9 . Red-Black Trees · Pat Morin
  13. 9 . 1 2-4 Trees · Pat Morin
  14. 9 . 2 RedBlackTree: A Simulated 2-4 Tree · Pat Morin
  15. 9 . 3 Summary · Pat Morin
  16. 9 . 4 Discussion and Exercises · Pat Morin
  17. 10 . Heaps · Pat Morin
  18. 10 . 1 BinaryHeap: An Implicit Binary Tree · Pat Morin
  19. 10 . 2 MeldableHeap: A Randomized Meldable Heap · Pat Morin
  20. 10 . 3 Discussion and Exercises · Pat Morin

Open in My Learning to record progress →