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

Solve the small states first.

Choose a dependency order and retain only the information the next state needs.

BY NAVAN SAMI◷ 8 MIN READSTRETCHALGORITHM

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.

THE THING THAT MUST STAY TRUE

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.

the_strategy.txt
INITIALISE the zero-step state
COMPUTE larger states from their solved smaller dependencies

03 Make it concrete

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

tabulation.py
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))
↳ EXPECTED OUTPUT
8
1
  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. 2

    The state is the target step count; its dependencies are the previous one and two counts. Increasing step order satisfies both.

  3. 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

TIME

O(n) states under unit-cost arithmetic

SPACE

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

A SMALL MISSION

Compress the recurrence to two running values and verify the same answers.

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), ways(0))

06 Check your reasoning

QUICK SIGNAL CHECK

What determines a valid DP evaluation order?

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.