Lesson 14 of 40More array patterns
Matrix Traversal and In-Place Tricks
Walk 2D grids with index maths, direction arrays and shrinking boundaries, and rotate, zero and update matrices in place with O(1) extra space.
Spreadsheets, images, game boards, seat maps, heat maps and warehouse floor plans are all 2D grids. Interviewers love them because the algorithms are short but the bugs are many: an off-by-one at a boundary, a row read after it was overwritten, a single-row input that walks back over itself. This lesson collects the grid moves you will be asked for most: index maths, neighbour loops, spirals, rotation, in-place marking tricks, diagonals and searching sorted matrices. Grids as graphs (flood fill, BFS on cells) is covered in Graphs; here the focus is on the matrix itself.
Coordinates, flat indices and neighbours
A grid with R rows and C columns is usually stored row-major: row 0, then row 1, and so on. That is how a list of lists reads, how C and NumPy lay out arrays by default, and how an image buffer is stored. Cell (r, c) has flat index r * C + c, because r full rows of C cells come before it. Going back is divmod(i, C), which gives (i // C, i % C). Note that both directions use the number of columns, not rows. Mixing them up works by accident on square grids and fails on the first rectangular test.
Flat indices are useful far beyond interviews. They let you store a grid in a single list, use cells as keys in a union-find, put cells in a set cheaply, and treat a sorted matrix as one sorted array.
For neighbours, never write four copies of the same if. Use a direction array and one bounds check.
Press Run (⌘ Enter) to see what happens.Watch Python's negative indexing. grid[-1][0] is not an error, it is the last row. A missing bounds check in Python silently wraps around to the other side of the grid instead of crashing, which is much harder to debug than an exception. Always check 0 <= r explicitly. And build grids with [[0] * C for _ in range(R)], never [[0] * C] * R, which makes every row the same list.
Spiral order with four shrinking boundaries
"Return all elements in spiral order." Keep four boundaries: top, bottom, left, right. Walk the top row and move top down. Walk the right column and move right in. Walk the bottom row backwards and move bottom up. Walk the left column upwards and move left in. Repeat while top <= bottom and left <= right.
Top row, left to right: 1 2 3 4. Then top moves from 0 to 1.
Press Run (⌘ Enter) to see what happens.The two if guards are the whole trap. After walking the top row and right column, the remaining region may have collapsed to nothing. A square input never shows it, so your first test passes. A single row or a single column does.
What does this print?
def spiral_no_guards(m):
out = []
top, bottom, left, right = 0, len(m) - 1, 0, len(m[0]) - 1
while top <= bottom and left <= right:
for c in range(left, right + 1): out.append(m[top][c])
top += 1
for r in range(top, bottom + 1): out.append(m[r][right])
right -= 1
for c in range(right, left - 1, -1): out.append(m[bottom][c])
bottom -= 1
for r in range(bottom, top - 1, -1): out.append(m[r][left])
left += 1
return out
print(spiral_no_guards([[1, 2, 3]]))Rotate Image in place
"Rotate an n × n matrix 90 degrees clockwise, in place." The formula is new[c][n - 1 - r] = old[r][c], but writing it directly in place overwrites cells you still need. There are two standard ways around that.
Transpose, then reverse each row. Transposing swaps (r, c) with (c, r), which mirrors across the main diagonal. Reversing each row mirrors left to right. Two mirrors make a rotation. Both steps are simple swaps, so each is safe in place. Only swap the upper triangle (c > r) when transposing, or you swap every pair twice and end up where you started.
The original. The main diagonal (1, 5, 9) is the mirror line for the transpose and never moves.
Ring by ring, four-way swap. Process each square ring from the outside in. For each position along the top edge, move four cells at once: left to top, bottom to left, right to bottom, saved top to right. It does the same work with one pass and one temporary variable, and it is the version to know if the interviewer asks for "a single pass" or a non-square variant of the idea.
Other rotations. Counter-clockwise is transpose then reverse the order of the rows (or reverse each row then transpose). A 180 degree turn is reverse the order of the rows and reverse each row, with no transpose. If you forget which is which, rotate a 2 × 2 on paper. It takes ten seconds and settles it.
Press Run (⌘ Enter) to see what happens.The loop at the bottom checks both in-place versions against the plain formula on sizes 1 to 6, including odd sizes where the centre cell must stay put. Writing the easy out-of-place version first and using it as a test oracle is how you gain confidence in a tricky in-place one.
Set Matrix Zeroes in O(1) extra space
"If a cell is 0, set its whole row and column to 0, in place." Setting zeros as you scan is wrong: a new zero then spreads to rows and columns that should not change. The O(R + C) fix is to record zero rows and columns in two sets, then apply. The O(1) fix reuses the matrix's own first row and first column as the marker storage.
The catch is that m[0][0] would have to mark both row 0 and column 0, and the markers overwrite the first row and column's real values. So record, before anything else, whether row 0 and column 0 originally contained a zero, in two booleans. Then mark, then zero the inner cells, and only at the very end zero row 0 and column 0 if their flags say so.
Zeros at (1,1) and (2,3). Row 0 and column 0 have no zero, so both flags start False.
Press Run (⌘ Enter) to see what happens.Many published solutions use one flag plus m[0][0] for the other. That works but is easy to get subtly wrong. Two named booleans cost nothing and read clearly, which is what you want under pressure.
Put the O(1)-space Set Matrix Zeroes steps in order.
- Tap the steps below in the right order.
Game of Life in place: two states in one cell
Conway's Game of Life updates every cell at once from its eight neighbours. Updating in place in reading order breaks that: by the time you reach a cell, some of its neighbours already hold next-turn values. The copy-the-board version is easy. The in-place follow-up wants O(1) extra space.
The trick: cells only use the values 0 and 1, so there is room for more bits. Keep the current state in bit 0 and write the next state into bit 1. When counting neighbours, read only cell & 1. After the full pass, shift every cell right by one so the next state becomes the current one.
Press Run (⌘ Enter) to see what happens.The same "encode old and new in one value" idea solves other in-place problems: marking visited cells by negating values (First Missing Positive), or using a sentinel like "#" during a flood fill and restoring it afterwards. In production code, prefer a copy unless memory genuinely matters. The in-place version is harder to read, and that cost is real.
cell & 1 rather than cell?Diagonals: r - c and r + c
Every cell on a top-left to bottom-right diagonal has the same r - c. Every cell on a top-right to bottom-left anti-diagonal has the same r + c. An R × C grid has R + C - 1 of each. Those two keys turn diagonal problems into hash-map or array problems.
- N-Queens. A queen attacks along its column, its
r - cdiagonal and itsr + canti-diagonal. Keep three sets, and a placement is legal in O(1). This is the check inside the backtracking from Backtracking. - Toeplitz Matrix. Every
r - cdiagonal must hold one value. Equivalently,m[r][c] == m[r - 1][c - 1]for every cell not in the first row or column, which streams one row at a time. - Diagonal Traverse. Group values by
r + c, then emit the groups in order, reversing every other one for the zigzag.
Press Run (⌘ Enter) to see what happens.r - c ranges from -(C - 1) to R - 1. In Python, a dict or set handles negative keys. If you use an array instead, add an offset of C - 1.
Searching sorted matrices: two different problems
These two LeetCode problems have almost the same name and need different algorithms. Interviewers use that on purpose.
Search a 2D Matrix. Each row is sorted, and the first value of each row is greater than the last value of the previous row. Read in row-major order, the whole matrix is one sorted list. Binary search over flat indices 0 to R * C - 1, and convert each mid to a cell with divmod(mid, C). That is O(log(R · C)).
Search a 2D Matrix II. Rows are sorted left to right and columns are sorted top to bottom, but rows can overlap. The flattened list is not sorted, so flat binary search is wrong. Start at the top-right corner. If the value is too big, everything below it in that column is bigger too, so move left. If it is too small, everything to its left in that row is smaller, so move down. Each step discards a whole row or column, so it takes at most R + C - 1 steps: O(R + C). The bottom-left corner works the same way. The top-left and bottom-right do not, because from there both moves go in the same direction.
Start at 15. It is bigger than 5, and everything below it in column 4 is even bigger. Drop the column: move left.
Press Run (⌘ Enter) to see what happens.Valid Sudoku: naming the boxes
Valid Sudoku checks that no digit repeats in any row, column or 3 × 3 box. Rows and columns are easy to index. For boxes, number them 0 to 8 in row-major order: box row r // 3, box column c // 3, so the box index is (r // 3) * 3 + c // 3. This is the same row * width + col flattening from the start of the lesson, applied to a 3 × 3 grid of boxes.
Press Run (⌘ Enter) to see what happens.Note the test that only clashes inside a box. A solution with a wrong box formula passes the row and column tests and fails only there, so always include one.
Match each grid task to the key or formula it needs.
What seniors watch for
- Rectangular inputs. Test 1 × n, n × 1 and 1 × 1 every time. Most grid bugs hide in shapes a square example never shows.
- Rows versus columns.
len(grid)is the row count,len(grid[0])is the column count, and an empty grid has nogrid[0]. Ask whether the input can be empty. - In place or not. "In place" in an interview usually means O(1) extra space. At work, mutating a caller's matrix is a surprise for whoever calls your function. Document it, or return a new matrix.
- Cache behaviour. Row-major storage means walking a row touches neighbouring memory, while walking a column jumps by a whole row each step. In Python this rarely matters, but in C, Java or NumPy, looping columns in the inner loop of a large matrix can be several times slower. The same idea is why image libraries and databases care about storage order.
Practice
These are in Practice: Spiral Matrix, Rotate Image, Set Matrix Zeroes, Search a 2D Matrix, Search a 2D Matrix II, Valid Sudoku, Kth Smallest Element in a Sorted Matrix and Count Negative Numbers in a Sorted Matrix. The last one is the staircase search again, from a different corner. For each, write down the shapes you will test before you start.
- row-major order
- Storing a grid row after row, so cell (r, c) sits at flat index r * cols + c.
- direction array
- A list of (dr, dc) offsets, used to loop over 4 or 8 neighbours with one bounds check.
- transpose
- Mirroring a matrix across its main diagonal by swapping (r, c) with (c, r).
- in-place marker
- Storing extra information inside the input itself, such as row 0 as zero markers, to avoid extra space.
- anti-diagonal
- A top-right to bottom-left line of cells. All its cells share the same r + c.
- staircase search
- Searching a row- and column-sorted matrix from a corner, discarding a row or column per step, in O(R + C).