Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Dynamic programming
EXPERIMENT 57 / 66

Do the work once.

Recognise overlapping subproblems and avoid recomputing the same answer.

BY NAVAN SAMI◷ 8 MIN READSTRETCHALGORITHM

01 Model the idea

Dynamic programming saves results of overlapping subproblems. Top-down memoization adds a cache to a recursive solution; bottom-up tabulation fills results in an order where dependencies are already available. The technique requires a well-defined state and a recurrence. Caching arbitrary code is not automatically correct, especially when results depend on changing external data.

THE THING THAT MUST STAY TRUE

Each cached value answers exactly the state used as its key.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
DEFINE base cases
LOOK UP an already solved state
OTHERWISE solve dependencies and cache the result

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

dynamic_programming.py
from functools import lru_cache
@lru_cache(maxsize=None)
def ways(steps):
    if steps < 0: return 0
    if steps == 0: return 1
    return ways(steps - 1) + ways(steps - 2)
print(ways(5))
print(ways.cache_info().currsize)
↳ EXPECTED OUTPUT
8
7
  1. 1

    ways(n) counts routes using one- or two-step moves. The two base cases define a valid empty route and impossible negative routes.

  2. 2

    Without caching, many calls repeat. The cache stores each distinct integer state, reducing the number of evaluated states to linear growth here.

  3. 3

    A bottom-up version can keep only the two most recent values, using constant auxiliary storage. Choose a state that captures everything the answer depends on, and account for potentially large integer arithmetic in detailed performance analysis.

04 Count the cost

TIME

O(n) distinct states under unit-cost arithmetic

SPACE

O(n) cache and recursive stack

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Implement the same count bottom-up with two running values.

Reveal one possible solution +
one_possible_solution.py
def ways(steps):
    if steps < 0: return 0
    previous, current = 1, 1
    for _ in range(steps):
        previous, current = current, previous + current
    return previous
print(ways(5))

06 Check your reasoning

QUICK SIGNAL CHECK

What makes memoization useful here?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.