Do the work once.
Recognise overlapping subproblems and avoid recomputing the same answer.
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.
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.
DEFINE base cases
LOOK UP an already solved state
OTHERWISE solve dependencies and cache the result03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
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)8 7
- 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
Without caching, many calls repeat. The cache stores each distinct integer state, reducing the number of evaluated states to linear growth here.
- 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
O(n) distinct states under unit-cost arithmetic
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
Implement the same count bottom-up with two running values.
Reveal one possible solution +
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
What makes memoization useful here?
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.