Sub topic 8
Measuring Time and Space
This chapter assumes you can read Big-O notation, write nested loops over a 2D list in Python, and follow the unique-paths and minimum-cost recurrences from earlier chapters. The goal is a repeatable way to price any grid DP before you write it, so you can tell whether it will finish in time and fit in memory.
The Core Formula
Every DP solution, on a grid or not, does two things. It computes each state once, and it stores states until nothing needs them anymore. Its cost follows from those two facts:
- Time = (number of states) × (work per state)
- Space = (number of states kept alive at once) + (any recursion stack)
On a grid, a state is usually one cell (i, j), so an m × n grid has m · n states. The work per state is the number of transitions the recurrence reads, plus any constant overhead. For unique paths that is two reads (top and left) and one addition, so the work per state is O(1).
The formula works because DP never revisits a finished state. The loop body runs once per cell, and each run does a fixed amount of work. Grid DP running time is therefore easy to predict: count the loop iterations and multiply.
Seeing the Difference: Brute Force vs Table
Without memoization, the path-counting recursion recomputes the same cells again and again. The script below counts how many function calls the plain recursion makes and how many cell updates the table makes, so you can see the gap directly.
from math import comb
def brute_paths(i, j, counter):
counter[0] += 1
if i == 0 or j == 0:
return 1
return brute_paths(i - 1, j, counter) + brute_paths(i, j - 1, counter)
def table_paths(m, n, counter):
dp = [[1] * n for _ in range(m)]
for i in range(1, m):
for j in range(1, n):
counter[0] += 1
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[m - 1][n - 1]
for size in (4, 8, 12):
brute_calls, table_ops = [0], [0]
r1 = brute_paths(size - 1, size - 1, brute_calls)
r2 = table_paths(size, size, table_ops)
assert r1 == r2 == comb(2 * size - 2, size - 1)
print(size, r1, brute_calls[0], table_ops[0])
# 4 20 39 9
# 8 3432 6863 49
# 12 705432 1410863 121The brute-force call tree is a full binary tree whose leaves each return 1. So it has exactly as many leaves as there are paths, C(m+n-2, m-1), and about twice that many calls in total. That count grows exponentially with grid size: a 16 × 16 grid already needs over 300 million calls. The table does (m-1)(n-1) updates no matter how many paths exist. That difference is the whole reason to use DP.
Pricing the Problems in This Tutorial
The same arithmetic covers every problem in the tutorial. Here are the costs side by side, including some that later chapters cover in detail.
| Problem | State | Number of states | Transitions per state | Time | Space (full table) |
|---|---|---|---|---|---|
| Unique paths | cell `(i, j)` | `m · n` | 2 | `O(mn)` | `O(mn)` |
| Paths with obstacles | cell `(i, j)` | `m · n` | 2 | `O(mn)` | `O(mn)` |
| Minimum path sum | cell `(i, j)` | `m · n` | 2 | `O(mn)` | `O(mn)` |
| Maximal square | cell `(i, j)` | `(m+1)(n+1)` | 3 | `O(mn)` | `O(mn)` |
| Edit distance | prefix pair `(i, j)` | `(m+1)(n+1)` | 3 | `O(mn)` | `O(mn)` |
| Dungeon game | cell `(i, j)` | `(m+1)(n+1)` | 2 | `O(mn)` | `O(mn)` |
| Longest increasing path | cell `(i, j)` | `m · n` | 4 | `O(mn)` | `O(mn)` |
| Cherry pickup | step and two rows `(k, r1, r2)` | about `2n · n · n` | 4 | `O(n³)` | `O(n³)` |
Padding rows and columns add m + n + 1 cells, which Big-O ignores. Constant transition counts (2, 3, 4) disappear from Big-O too, but they still matter in practice. A recurrence that reads three neighbors and takes a min costs noticeably more per cell than one that adds two numbers.
The last row shows a jump in cost. Once a state holds more than one cell's coordinates, each extra coordinate multiplies the state count by roughly another factor of n. Cherry pickup's state has three coordinates, so it is cubic.
Space: What You Actually Store
A full table uses O(mn) space. That is often more than the problem needs, because most recurrences only read the previous row. A later chapter turns that fact into a one-row solution that uses O(n) space. For now, note when the reduction is allowed and when it is not:
- Allowed when you need only the final value and each row depends on the row directly above it.
- Not allowed without extra work when you must reconstruct the optimal path afterward. Backtracking reads arbitrary earlier cells, so you keep the whole table (or a separate table of choices).
Concrete memory, not just Big-O
In Python, a list of lists of size m × n stores one 8-byte pointer per entry, plus the int or float objects those pointers refer to. A 1000 × 1000 grid uses about 8 MB for pointers alone. Small integers from -5 to 256 are cached and shared, but larger values each take their own object of 28 bytes or more. If memory is tight, the one-row trick, or an array or NumPy array of fixed-width numbers, cuts this a lot.
Recursion stack for top-down solutions
A memoized solution has the same number of states as the table. On top of that it uses a call stack as deep as the longest chain of pending calls. For right/down moves, that chain can reach m + n - 1 frames. Python's default recursion limit is 1000, so a 600 × 600 grid can crash a memoized solution that a loop handles easily. The memoization chapter covers this trade-off fully. When you price a top-down solution, add the stack depth to the space cost.
When Numbers Get Big
Big-O usually assumes each arithmetic operation takes constant time. Path counting breaks that assumption, because the counts themselves grow exponentially.
def count_paths(m, n):
dp = [[1] * n for _ in range(m)]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[m - 1][n - 1]
answer = count_paths(100, 100)
print(len(str(answer))) # 59Python integers have no size limit, so this gives the right answer. But adding two 59-digit numbers costs more than adding two small ones, and every cell near the bottom-right holds a large integer. In C++ or Java the same code would silently overflow a 64-bit integer. That is why many problem statements ask for the answer "modulo 10⁹ + 7". Taking the modulus after each addition keeps every number small and restores true O(1) arithmetic.
A Checklist for Any Grid DP
- Write down the state and count how many distinct values it can take. That gives the number of states.
- Count the transitions the recurrence reads. That gives the work per state.
- Multiply the two to get the time.
- Decide what you must keep: the full table, one row, or a table of choices for reconstruction. That gives the space.
- For top-down solutions, add the maximum recursion depth.
- For counting problems, check whether the values outgrow fixed-width integers.
Run this checklist before coding. Then, if the time estimate is around 10⁸ simple operations or more in Python, look for a smaller state before you start fixing code.
Exercise
A robot moves on an m × n grid and can step right, down, or diagonally down-right. You count the paths from the top-left to the bottom-right with a bottom-up table. What are the time and space complexities, and how many neighbor reads happen in total for a 50 × 80 grid, ignoring cells in the first row and first column?
Show answer
Each cell reads three neighbors (top, left, top-left), so time is O(mn) and space is O(mn) for the full table, or O(n) with a rolling row. Excluding the first row and column leaves 49 × 79 = 3871 cells, giving 3 × 3871 = 11613 neighbor reads.
Exercise
You solve minimum path sum top-down with lru_cache on a 2000 × 2000 grid. The number of cached states is fine, but the program crashes. Explain the crash in terms of space cost and give two fixes.
Show answer
The memoized recursion can nest up to m + n - 1 = 3999 calls deep before reaching the base case, which exceeds Python's default recursion limit of 1000 and raises RecursionError. Fixes: rewrite it as a bottom-up loop, which needs no recursion stack, or raise the limit with sys.setrecursionlimit and run the code in a thread with a larger stack size. The bottom-up rewrite is the more reliable fix.
Exercise
A variant tracks a walker's cell and how many of k bonus tokens it still holds, so the state is (i, j, t) with 0 ≤ t ≤ k. Each state has two moves, and each move either keeps or spends a token. Give the time complexity and say whether a one-row space reduction still applies.
Show answer
There are m · n · (k + 1) states, each with at most four transitions (two moves times two token choices), so time is O(mnk). Each state still depends only on the row above and on cells to its left in the current row, so you can keep one row of size n × (k + 1), which uses O(nk) space.