Sub topic 11
How Much Time and Space 2D Operations Take
This chapter assumes you can write nested loops and read Big-O notation such as O(n). It also assumes you know the 2D operations from earlier chapters: traversal, transpose, and matrix multiplication. Here you will put a cost on each one.
Naming the sizes
Let a grid have m rows and n columns. It holds m * n cells. Each cost below is written in terms of m and n. For a square matrix, m = n, so m * n becomes n².
Cost of single operations
Reading or writing grid[r][c] takes O(1) time. Python finds the row list, then the cell in that row. Neither step depends on the grid size.
Visiting every cell takes O(m·n) time, because the inner body runs once per cell. Nested loops do not always mean quadratic cost in n. The cost is the product of the two loop bounds.
Creating a grid also takes O(m·n) time and space, because every cell must exist. The shared-row version [[0] * n] * m stores only one real row of n cells, but it is a bug, not a space saving.
Time and space together
Space has two parts. The first is the input, which you usually do not count. The second is the extra memory your function allocates.
| Operation | Time | Extra space |
|---|---|---|
| Read or write one cell | O(1) | O(1) |
| Full traversal | O(m·n) | O(1) |
| Row sums | O(m·n) | O(m) |
| Column sums | O(m·n) | O(n) |
| Transpose (new grid) | O(m·n) | O(m·n) |
| Addition of two m×n matrices | O(m·n) | O(m·n) |
| Neighbors of one cell | O(1) | O(1) |
| Multiply (m×k) by (k×p) | O(m·k·p) | O(m·p) |
Row sums need only one number per row, so extra space is O(m). A transpose must build a whole new grid, so it costs O(m·n) space. A square matrix can be transposed in place by swapping grid[r][c] with grid[c][r] for c > r. That uses O(1) extra space, but it does not work for a non-square grid.
Neighbor checks are O(1) because a cell has at most four neighbors in the four-direction version. A flood fill over a whole grid still costs O(m·n), because each cell is visited a bounded number of times.
Why multiplication is the expensive one
Matrix multiplication has three nested loops. The result has m·p cells, and each one needs a dot product of length k. The code below counts how many times the innermost line would run.
def count_matmul_steps(n, m, p):
steps = 0
for i in range(n):
for j in range(p):
for k in range(m):
steps += 1
return steps
print(count_matmul_steps(10, 10, 10)) # 1000
print(count_matmul_steps(20, 20, 20)) # 8000
print(count_matmul_steps(2, 3, 4)) # 24Doubling the side of a square matrix from 10 to 20 multiplies the work by 8, not 2. This is O(n³) growth. Faster algorithms exist, but the simple triple loop is the standard one for small and medium sizes.
Practical gotchas
- Column-first loops can be slower. Row-major order follows the way each row list is stored, which is usually friendlier to the CPU cache. Both orders are O(m·n), but the constant factor differs.
- Copies add space.
[row[:] for row in grid]costs O(m·n) space. Building a new grid in each step of a loop can multiply that cost. - Jagged grids change the formula. If rows have different lengths, total time is the sum of the row lengths, not
m * n. - Library code has the same Big-O but a lower constant. NumPy runs the loops in compiled code, so the counts above still apply, but each step is much cheaper.
Exercise
A function takes an n×n grid and returns a new grid that is its transpose. What are its time and extra space, and how could you reduce the extra space?
Show answer
Time is O(n²) because every cell is copied once. Extra space is O(n²) for the new grid. For a square grid you can transpose in place by swapping grid[r][c] and grid[c][r] for c > r, which brings extra space down to O(1) while keeping time at O(n²).