On this page · Define a Cell before Choosing a Loop
Tabulation
Give each DP state a precise meaning, seed valid base states, and fill in an order that makes every dependency final. Compress history only after proving no later transition needs it.
Recognize it when A finite acyclic recurrence reuses previously solved states.
Checking your account…
Tabulation Code Labs
Define a Cell before Choosing a Loop
Tabulation is a dependency schedule for a recurrence. A Fibonacci cell at index i contains F(i), with F(0)=0 and F(1)=1. A stair-count cell instead contains the number of ordered one/two-step paths ending at i. Its step-zero value is 1: the empty sequence is one way to stay there. Similar recurrences can therefore need different bases.
Fill Only after Both Dependencies
The table Lab iterates indices upward. Filling i reads i-1 and i-2, which have already been finalized. Reversing that order would read default zero entries as if they were solved answers. The initial snapshot includes future zero placeholders; those positions are not yet claimed to equal Fibonacci values.
Trace Bottom-Up Table Fills
Reference
def fibonacci_table(n):
table=[0]*(n+1)
if n>=1: table[1]=1
trace=[table.copy()]
for index in range(2,n+1):
table[index]=table[index-1]+table[index-2]; trace.append(table.copy())
return trace
Practice
Implement fibonacci_table(n) for a nonnegative integer n. Return the table after each index 2 through n is filled, including the initial base table.
Public tests
Fill only after dependencies
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Trace Bottom-Up Table Fills
def fibonacci_table(n):
table=[0]*(n+1)
if n>=1: table[1]=1
trace=[table.copy()]
for index in range(2,n+1):
table[index]=table[index-1]+table[index-2]; trace.append(table.copy())
return trace
Distinguish Unfilled Zeroes from Final Values
Predict fibonacci_table(4). The table starts with bases only, then one final value is added at each increasing index.
Step
Executed statement
State
Why
1
table=[0]*(n+1); table[1]=1; trace=[table.copy()]
table=[0,1,0,0,0]
Only indices 0 and 1 are solved bases; later zeroes are placeholders.
Each snapshot copies the entire table, including cells not yet filled. The core recurrence has n updates, but n copies of length n produce O(n²) diagnostic work and output. Saving only the final table would cost O(n) entries.
Compress the Stair Count after Its Meaning Is Clear
For step i, the final move is either one step from i-1 or two from i-2. These cases are disjoint and cover every path, so their counts add. Only those two predecessors are needed, allowing previous and current to replace a full table. Tuple assignment computes both new values from the old pair before overwriting either.
Count Stair Ways
Reference
def count_stair_ways(n):
if n<2: return 1
previous,current=1,1
for _ in range(2,n+1): previous,current=current,previous+current
return current
Practice
Implement count_stair_ways(n) for a nonnegative integer n. Return ways to reach step n using moves of one or two, with one way to remain at step zero.
Public tests
Compress dead table history
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Count Stair Ways
def count_stair_ways(n):
if n<2: return 1
previous,current=1,1
for _ in range(2,n+1): previous,current=current,previous+current
return current
Both n=0 and n=1 have one stair path. The Labs assume a nonnegative integer n. No path reconstruction is requested; reconstructing a chosen path or reading distant states could require retaining more history.
Select the Evaluation Order in an Interview
Bottom-up DP and memoization can solve the same acyclic recurrence. Tabulation gives explicit iteration, avoids a deep recursive stack, and makes rolling-state opportunities visible. Memoization can win when only a small portion of a larger state space is reachable. Explain states, bases and dependencies before claiming O(n) time or constant rolling-entry space; Python’s growing integer representations add arithmetic and byte-storage costs for very large counts.
Templates To Memorize
Learn this shape by heart; most problems in this family change only one or two lines of it.
1D dynamic programming
State, choice, base case, then fill in order.
The answer for step i depends on the answers for a few earlier steps.
Trigger words
ways to climb
no two adjacent
house robber
decode ways
longest increasing subsequence
best up to index i
def climb_stairs(n):
if n <= 2:
return n
dp = [0] * (n + 1) # dp[i] = number of ways to reach step i
dp[1] = 1
dp[2] = 2
for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 2] # arrive from one step or two steps below
return dp[n]
Spot it when
'How many ways to reach ...', 'maximum you can rob'.
Choices at each step with overlapping subproblems.
Remember
Say the state in words first: 'dp[i] is ...'.
Once it works, you can keep only the last two values to use O(1) space.
How problems bend it
House robber (take it or skip it): dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]): skip this house or rob it.
Houses in a circle: Run the same DP twice: without the first house and without the last house.
Decode ways: dp[i] = ways to decode the first i characters: add dp[i - 1] when the last digit is 1-9, and dp[i - 2] when the last two digits are 10-26.
Knapsack-style DP over amounts
0/1 goes backward, unbounded goes forward.
You pick items (coins, numbers) to reach a target total, and want the count of ways, the fewest items, or whether it is possible.
Trigger words
coin change
make up the amount
target sum
partition equal subset
each item once
unlimited coins
def fewest_squares(n):
squares = [k * k for k in range(1, int(n ** 0.5) + 1)]
dp = [0] + [n + 1] * n # dp[x] = fewest squares that sum to x
for x in range(1, n + 1): # unbounded: amounts go forward
for square in squares:
if square > x:
break
dp[x] = min(dp[x], dp[x - square] + 1)
return dp[n]