Exercise 30 of 30 · beginner · space · quadratic · dynamic programming
Filling an n × n table
The code
table = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, n + 1):
table[i][j] = table[i-1][j] + table[i][j-1]What is the auxiliary space?
Count: cells allocated.
Measured counts
Table
| n | count |
|---|---|
| 8 | 81 |
| 16 | 289 |
| 32 | 1,089 |
| 64 | 4,225 |
| 128 | 16,641 |
| 256 | 66,049 |
| 512 | 263,169 |
Try to name the class from the shape before opening the answer.
Show the answer and derivation
- Time
- Θ(n²)
- Extra space
- Θ(n²), reducible to Θ(n)
- Exact count
- (n + 1)²
- The table has (n + 1)² cells: Θ(n²) space.
- Each row depends only on the previous row, so two rows (or one, updated in place) suffice: Θ(n) space with the same Θ(n²) time.
- This space optimisation is a standard step in dynamic programming (M32).
Common mistake: Reporting only time. Space is a separate bound and often the binding constraint.
Check: measured count ÷ (n²) settles near 1.00 for large n.