Grids & Matrices
Grids are 2D arrays whose cells can represent boards, images, terrain, graphs, or numeric matrices. Interview questions usually test whether you can keep row/column coordinates, movement rules, and traversal order precise.
1. Coordinates and Safe Access
For a rectangular R x C grid:
R = len(grid)andC = len(grid[0]).- Dimensions are written rows first, columns second.
- Use
grid[r][c], notgrid[x][y]:rselects a row andcselects a column. - The top-left cell is
grid[0][0]; the bottom-right isgrid[R - 1][C - 1].
Build and copy grids safely
In Python, create independent rows with [[0] * C for _ in range(R)] and copy with [row.copy() for row in grid]. Avoid [[0] * C] * R: every row aliases the same list.
Validate before reading
Keep bounds and problem-specific rules in one helper. The bounds check must come first so the cell access cannot go out of range.
def is_valid(grid, r, c):
R, C = len(grid), len(grid[0])
return (
0 <= r < R
and 0 <= c < C
and grid[r][c] != BLOCKED
)
2. Moving Through a Grid
A directions array turns repeated row/column arithmetic into data:
- Four neighbors:
(-1, 0), (1, 0), (0, -1), (0, 1). - Add four diagonals for eight-way movement.
- Knight moves use eight
(±2, ±1)/(±1, ±2)offsets. - Sliding pieces or rays keep applying the same offset until blocked.
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for dr, dc in directions:
nr, nc = r + dr, c + dc
if is_valid(grid, nr, nc):
visit(nr, nc)
Iterating over a fixed directions list is per cell. A full DFS or BFS is usually because each cell is visited at most once. Mark cells as visited when they are discovered so they are not queued or explored repeatedly.
3. Tracing Movement Patterns
Some questions are about pointer motion rather than graph search. Track the complete state—usually (r, c, direction)—and write down exactly when it changes.
Spirals and turns
For a spiral, move forward while the next cell is valid and unused; otherwise rotate the direction. With four directions, direction = (direction + 1) % 4 handles wraparound cleanly. Sometimes reversing the construction makes the starting point and turn rule much simpler.
Static pattern
Move forward; turn only when blocked
The path is a rule, not a replay
Continue in the current direction while the next cell is valid and unused. At each amber turn, rotate clockwise and continue.
- 1.Track
(row, column, direction). - 2.Test the next cell before moving.
- 3.Rotate with
(direction + 1) % 4when blocked.
Follow the constrained path
Do not scan all cells when the input guarantees a narrow path. If each column contains one footprint and the next footprint can only be one row up, level, or one row down, find the starting row once and test only those three candidates in each next column. That improves to .
Static shortcut
Trace the guarantee instead of scanning the grid
From the current row, inspect only the three neighboring rows in the next column.
O(R + C)Let dependencies choose the scan order
Use row-major order for ordinary scans, reverse order when a cell depends on values below or to the right, and layer-by-layer order for BFS. The correct traversal is the one that makes required information available when you need it.
Static comparison
Choose the order that makes dependencies ready
Row-major
Independent work: left to right, then next row.
Bottom-right first
Suffix DP: below and right are already ready.
BFS layers
Shortest paths: process one distance layer at a time.
(2, 2): its below and right dependencies are already ready. BFS groups cells by distance from the start.4. Subgrids and Reusing Work
A subgrid is a rectangular region inside the grid. Keep its boundaries explicit: top-left (r1, c1), bottom-right (r2, c2).
Validate a partially filled 9×9 board
A common interview task is to determine whether a partially filled board is currently valid—not to solve it. Each cell is empty or contains a digit from 1 to 9. Ignore empty cells. Every filled value must appear at most once in:
- Its row.
- Its column.
- Its 3×3 block.
Scan each filled cell (r, c) and track seen values for its row, column, and block. The block is identified by (r // 3, c // 3). If the value already exists in any corresponding set, the board is invalid.
Board validation
Is this partially filled 9×9 board valid?
Selected cell: value 5 at (4, 4)
The task
Decide whether the current board is valid. Ignore empty cells; do not try to solve the puzzle.
Row 4
The value 5 appears once
Column 4
The value 5 appears once
3×3 block (1, 1)
Check all filled values
(r // 3, c // 3) block.Answer bottom-right region queries once
Suppose a query starts at (r, c) and asks about the complete rectangle from that cell to the grid's bottom-right corner. Rescanning that rectangle for every possible starting cell repeats the same work. Instead, build one output table whose cell (r, c) stores the answer for that rectangle.
Fill the output table from bottom-right to top-left. Start at (R - 1, C - 1), sweep right-to-left across each row, then move up one row. That order guarantees the smaller regions below and to the right are already available before they are referenced.
Suffix maximum
M[r][c] stores the largest input value in the rectangle from (r, c) to the bottom-right. Its recurrence reads the cell below and the cell to the right, so compute those cells first with the bottom-right-to-top-left order:
M[r][c] = max(grid[r][c], M[r + 1][c], M[r][c + 1])
Suffix maximum
Find the maximum in every bottom-right rectangle
Question: what is the largest value in the highlighted rectangle?
For (3, 3), use every input cell from that coordinate to the bottom-right corner.
Why fill from bottom-right?
Start at (R−1, C−1). It has no cell below or to the right, so it is the base case.
Sweep right to left. The cell to the right has already been computed.
Move up one row. The row below is now ready for every cell above it.
Input grid A
These are the original values from the problem.
Output table M
Each cell stores the answer for the same starting coordinate.
Current calculation
M[3][3] = max(A[3][3] = 0) = 0The green cells already summarize the rectangles below and to the right.
Suffix sum
S[r][c] stores the sum of all input values in that same rectangle. Compute from bottom-right to top-left so the regions below and to the right are ready. Those regions overlap at (r + 1, c + 1), so subtract that overlap once:
S[r][c] = grid[r][c] + S[r + 1][c] + S[r][c + 1] - S[r + 1][c + 1]
Suffix sum
Find the sum of every bottom-right rectangle
Question: what is the total in the highlighted rectangle?
For (3, 3), use every input cell from that coordinate to the bottom-right corner.
Why fill from bottom-right?
Start at (R−1, C−1). It has no cell below or to the right, so it is the base case.
Sweep right to left. The cell to the right has already been computed.
Move up one row. The row below is now ready for every cell above it.
Input grid A
These are the original values from the problem.
Output table S
Each cell stores the answer for the same starting coordinate.
Current calculation
S[3][3] = A[3][3] (0) = 0Add the ready regions below and right, then subtract their diagonal overlap once.
Each output table takes time and space to build. Afterward, any bottom-right maximum or sum query is a single table lookup.
5. Matrix Transformations
You do not need advanced linear algebra for general interviews, but you should know the basic transformations:
- Transpose: swap
matrix[r][c]withmatrix[c][r]. For an in-place square transpose, visit only one side of the main diagonal so each pair is swapped once. - Horizontal reflection: reverse every row.
- Vertical reflection: reverse the order of the rows.
- Clockwise rotation: transpose, then reflect horizontally.
- Counterclockwise rotation: transpose, then reflect vertically.
For addition and subtraction, matrices need matching dimensions and combine cell by cell. For multiplication, A shaped R x K times B shaped K x C produces R x C; each output cell is a row/column dot product. The order matters, and the direct algorithm takes time.
Interview Checklist
Before coding, answer these questions:
- What are
RandC, and can the grid be empty? - Which moves are allowed: four-way, diagonal, jumps, or rays?
- What makes a cell invalid: bounds, obstacles, visited state, or value?
- Should the input be mutated, copied, or left unchanged?
- What traversal order makes dependencies available?
- Can a structural guarantee let you trace only part of the grid?
- Is the expected complexity , or can preprocessing answer repeated region queries faster?
Practice Problems
Number of Islands
LeetCode: https://leetcode.com/problems/number-of-islands/
Flood Fill
LeetCode: https://leetcode.com/problems/flood-fill/
Rotting Oranges
LeetCode: https://leetcode.com/problems/rotting-oranges/
Chess Moves
This problem asks us to simulate the movement of three chess pieces: King, Knight, and Queen.
Queens That Can Attack the King
LeetCode: https://leetcode.com/problems/queens-that-can-attack-the-king/
Spiral Matrix
LeetCode: https://leetcode.com/problems/spiral-matrix/
Spiral Matrix II
LeetCode: https://leetcode.com/problems/spiral-matrix-ii/
Beyond Cracking the Coding Interview
Snowprints
We are tracking *Elsa*, an arctic fox, through a rectangular snowy field represented by a binary grid, field, where a 1 denotes snowprints and a 0 denotes no snowprints. We know that the fox crossed the field from left to right, so each column has exactly one 1.
Spiral Order (From Center)
Given a positive and odd integer n, return an n x n grid filled with integers from 0 to n^2 - 1 in spiral order.
Valid Sudoku
LeetCode: https://leetcode.com/problems/valid-sudoku/
Subgrid Maximums
Given a rectangular RxC grid of integers, grid, with R > 0 and C > 0, return a new grid with the same dimensions where each cell [r, c] contains the maximum in the subgrid with [r, c] in the top-left corner and [R - 1, C - 1] in the bottom-right corner.
Subgrid Sums
Given a rectangular RxC grid of integers, grid, with R > 0 and C > 0, return a new grid with the same dimensions where each cell [r, c] contains the sum of all the elements in the subgrid with [r, c] in the top-left corner and [R - 1, C - 1] in the bottom-right corner.
Matrix Operations (Rotate & In-place)
Given a square n x n matrix, return a new matrix that results from: