Solve the small states first.
Choose a dependency order and retain only the information the next state needs.
01 Model the idea
Bottom-up dynamic programming evaluates states in an order where their dependencies are already solved. The recurrence and base cases define the same problem as a top-down memoized version, but no recursion is required. Space can often be reduced when only a small recent slice of the table is needed, provided you do not also need the full reconstruction history.
Every table entry before the current state already has its final answer.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
INITIALISE the zero-step state
COMPUTE larger states from their solved smaller dependencies03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
def ways(steps):
if steps < 0: return 0
table = [0] * (steps + 1)
table[0] = 1
for step in range(1, steps + 1):
table[step] = table[step - 1]
if step >= 2: table[step] += table[step - 2]
return table[steps]
print(ways(5))
print(ways(0))8 1
- 1
The empty route gives one way to climb zero steps. This base case drives the recurrence correctly at steps one and two.
- 2
The state is the target step count; its dependencies are the previous one and two counts. Increasing step order satisfies both.
- 3
The table costs linear space. Two running values reduce auxiliary storage to constant-sized integer variables, though integer bit size grows with the count.
04 Count the cost
O(n) states under unit-cost arithmetic
O(n) table; O(1) state variables in compressed version
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
Compress the recurrence to two running values and verify the same answers.
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), ways(0))06 Check your reasoning
What determines a valid DP evaluation order?
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.