Skip to contentKEEP THE CRAFTTHE SANCTUARY

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.

2 practice exercises16 interview problems

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.
2 table[index]=table[index-1]+table[index-2]; trace.append(table.copy()) index=2; table=[0,1,1,0,0] Both required base values are already final.
3 table[index]=table[index-1]+table[index-2]; trace.append(table.copy()) index=3; table=[0,1,1,2,0] F(2) is now available to combine with F(1).
4 table[index]=table[index-1]+table[index-2]; trace.append(table.copy()) index=4; table=[0,1,1,2,3] The target uses the two just-completed predecessors.
Print Output
print(fibonacci_table(4)) [[0, 1, 0, 0, 0], [0, 1, 1, 0, 0], [0, 1, 1, 2, 0], [0, 1, 1, 2, 3]]

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]

Spot it when

  • 'Coin change', 'partition equal subset sum', 'target sum'.

Remember

  • dp[0] is the base case: nothing is needed to make zero.
  • Each item can be used once? Loop the amount from high to low so an item is not counted twice.

How problems bend it

  • Number of ways (coin change II): Put the coin loop outside and add: dp[x] += dp[x - coin], with dp[0] = 1.
  • Can a subset reach the target?: dp is a list of booleans; for each number, loop x downwards: dp[x] = dp[x] or dp[x - num].
  • Count ordered sequences (combination sum IV): Put the amount loop outside and the item loop inside; with items outside you count each set once.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Count one/two-step stair paths with rolling DPO(n)O(n)The stair recurrence performs one fixed-size state update per step.

Space

O(1) rolling entries under the unit-cost integer model; the Fibonacci snapshot Lab has O(n²) output.

Assumptions

  • fibonacci_table saves a length-(n+1) copy initially and after every fill, so its diagnostic time and space are O(n²).
  • An ordinary full Fibonacci or stair table uses O(n) entries; saving every whole-table version is an additional output cost.
  • Python integers grow with the answer, so literal O(1) byte space and unit-cost addition are not exact for unbounded n.

Invariants Worth Saying Aloud

  1. Each finalized table cell has the exact count or optimum promised by its state definition.
  2. Every dependency is finalized before its consumer is filled.
  3. Rolling variables hold the previous two stair counts before each simultaneous update.

When To Use Or Avoid Tabulation

Use It When

  • The state space is manageable and its dependency order is known.
  • Base values and unreachable sentinels can be distinguished for the objective being computed.

Choose Another Tool When

  • Most possible states are unreachable and top-down memoization can avoid allocating them.
  • Dependencies form a cycle without a separate fixed-point or graph formulation.
  • A recurrence requires older history that the proposed rolling variables would overwrite.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Using the Fibonacci zero base for stair paths

Zero ways to remain at step zero removes the empty path that later counts depend on.

Prevent it: Define the state meaning and seed one empty stair path.

Avoid

ways_at_zero=0

Use instead

ways_at_zero=1

Filling a consumer before its dependencies

Descending indices read an unfilled predecessor and leave a wrong value that is never revisited.

Prevent it: Use increasing indices for this predecessor recurrence.

Avoid

for index in [3,2]:
    table[index]=table[index-1]+table[index-2]

Use instead

for index in [2,3]:
    table[index]=table[index-1]+table[index-2]

Overwriting one rolling predecessor too early

Assigning previous first makes the second statement add the new previous to current, losing the older dependency.

Prevent it: Use simultaneous assignment or explicit saved old values.

Avoid

previous=current
current=previous+current

Use instead

previous,current=current,previous+current

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.