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

01.0e+2k2.0e+2k200400ncount
Measured
Table
ncount
881
16289
321,089
644,225
12816,641
25666,049
512263,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)²
  1. The table has (n + 1)² cells: Θ(n²) space.
  2. Each row depends only on the previous row, so two rows (or one, updated in place) suffice: Θ(n) space with the same Θ(n²) time.
  3. 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.