Skip to content

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.

17 min read0/5 questions

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.

Python
grid = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12],]ROWS, COLS = len(grid), len(grid[0]) def to_index(r, c): return r * COLS + c # row-major: row r starts after r full rows def to_cell(i): return divmod(i, COLS) # (i // COLS, i % COLS) DIRS4 = [(-1, 0), (1, 0), (0, -1), (0, 1)] # up, down, left, rightDIRS8 = DIRS4 + [(-1, -1), (-1, 1), (1, -1), (1, 1)] # plus the diagonals def in_bounds(r, c): return 0 <= r < ROWS and 0 <= c < COLS def neighbours(r, c, dirs=DIRS4): for dr, dc in dirs: nr, nc = r + dr, c + dc if in_bounds(nr, nc): yield nr, nc assert to_index(2, 1) == 9 and grid[2][1] == 10assert to_cell(9) == (2, 1)assert all(to_cell(to_index(r, c)) == (r, c) for r in range(ROWS) for c in range(COLS))assert sorted(neighbours(0, 0)) == [(0, 1), (1, 0)]assert len(list(neighbours(1, 1, DIRS8))) == 8assert len(list(neighbours(0, 3, DIRS8))) == 3print(to_index(2, 1), to_cell(9), list(neighbours(0, 0)))
Output
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.

Spiral order of a 3 × 4 grid
1234
5678
9101112

Top row, left to right: 1 2 3 4. Then top moves from 0 to 1.

1/5
Python
def spiral_order(matrix): out = [] top, bottom = 0, len(matrix) - 1 left, right = 0, len(matrix[0]) - 1 while top <= bottom and left <= right: for c in range(left, right + 1): # top row, left to right out.append(matrix[top][c]) top += 1 for r in range(top, bottom + 1): # right column, downwards out.append(matrix[r][right]) right -= 1 if top <= bottom: # a row is still left for c in range(right, left - 1, -1): # bottom row, right to left out.append(matrix[bottom][c]) bottom -= 1 if left <= right: # a column is still left for r in range(bottom, top - 1, -1): # left column, upwards out.append(matrix[r][left]) left += 1 return out assert spiral_order([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [1, 2, 3, 6, 9, 8, 7, 4, 5]assert spiral_order([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) == [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]assert spiral_order([[1, 2, 3]]) == [1, 2, 3] # single row: no doubling backassert spiral_order([[1], [2], [3]]) == [1, 2, 3] # single columnassert spiral_order([[7]]) == [7]print(spiral_order([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]))
Output
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.

Predict the outputPython

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]]))
Need a nudge? Hints walk you through it.

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.

Clockwise rotation = transpose + reverse rows
123
456
789

The original. The main diagonal (1, 5, 9) is the mirror line for the transpose and never moves.

1/3

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.

Python
def rotate_clockwise(m): n = len(m) for r in range(n): # 1. transpose: swap across the main diagonal for c in range(r + 1, n): m[r][c], m[c][r] = m[c][r], m[r][c] for row in m: # 2. reverse each row row.reverse() def rotate_counter_clockwise(m): n = len(m) for r in range(n): for c in range(r + 1, n): m[r][c], m[c][r] = m[c][r], m[r][c] m.reverse() # reverse the ORDER of rows instead def rotate_rings(m): """Clockwise, one 4-way swap per cell group, ring by ring.""" n = len(m) for layer in range(n // 2): first, last = layer, n - 1 - layer for i in range(first, last): off = i - first top = m[first][i] m[first][i] = m[last - off][first] # left -> top m[last - off][first] = m[last][last - off] # bottom -> left m[last][last - off] = m[i][last] # right -> bottom m[i][last] = top # top -> right def fresh(): return [[1, 2, 3], [4, 5, 6], [7, 8, 9]] a = fresh(); rotate_clockwise(a)assert a == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]b = fresh(); rotate_rings(b)assert b == ac = fresh(); rotate_counter_clockwise(c)assert c == [[3, 6, 9], [2, 5, 8], [1, 4, 7]] def by_formula(m): # clockwise: new[c][n-1-r] = old[r][c] n = len(m) out = [[0] * n for _ in range(n)] for r in range(n): for c in range(n): out[c][n - 1 - r] = m[r][c] return out for n in range(1, 7): base = [[r * n + c for c in range(n)] for r in range(n)] x = [row[:] for row in base]; rotate_clockwise(x) y = [row[:] for row in base]; rotate_rings(y) assert x == y == by_formula(base)print(a)
Output
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.

Using row 0 and column 0 as markers
1234
5078
910110
13141516

Zeros at (1,1) and (2,3). Row 0 and column 0 have no zero, so both flags start False.

1/4
Python
def set_zeroes(m): rows, cols = len(m), len(m[0]) first_row_zero = any(m[0][c] == 0 for c in range(cols)) first_col_zero = any(m[r][0] == 0 for r in range(rows)) # 1. use row 0 and column 0 as marker storage for the rest of the grid for r in range(1, rows): for c in range(1, cols): if m[r][c] == 0: m[r][0] = 0 m[0][c] = 0 # 2. zero the inner cells from the markers for r in range(1, rows): for c in range(1, cols): if m[r][0] == 0 or m[0][c] == 0: m[r][c] = 0 # 3. only now overwrite the marker row and column themselves if first_row_zero: for c in range(cols): m[0][c] = 0 if first_col_zero: for r in range(rows): m[r][0] = 0 def brute(m): zr = {r for r, row in enumerate(m) for v in row if v == 0} zc = {c for row in m for c, v in enumerate(row) if v == 0} return [[0 if r in zr or c in zc else v for c, v in enumerate(row)] for r, row in enumerate(m)] a = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]set_zeroes(a)assert a == [[1, 0, 1], [0, 0, 0], [1, 0, 1]]b = [[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]]set_zeroes(b)assert b == [[0, 0, 0, 0], [0, 4, 5, 0], [0, 3, 1, 0]]import randomrandom.seed(8)for _ in range(300): R, C = random.randint(1, 5), random.randint(1, 5) g = [[random.choice([0, 1, 1, 2, 3]) for _ in range(C)] for _ in range(R)] want = brute(g) set_zeroes(g) assert g == wantprint(b)
Output
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 it in order4 steps

Put the O(1)-space Set Matrix Zeroes steps in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

Python
def game_of_life(board): rows, cols = len(board), len(board[0]) # bit 0 = state now, bit 1 = state next turn for r in range(rows): for c in range(cols): live = 0 for dr in (-1, 0, 1): for dc in (-1, 0, 1): if (dr or dc) and 0 <= r + dr < rows and 0 <= c + dc < cols: live += board[r + dr][c + dc] & 1 # read ONLY the old bit if board[r][c] & 1 and live in (2, 3): board[r][c] |= 2 # survives elif not board[r][c] & 1 and live == 3: board[r][c] |= 2 # born for r in range(rows): for c in range(cols): board[r][c] >>= 1 # the new bit becomes the state def copy_version(board): rows, cols = len(board), len(board[0]) out = [[0] * cols for _ in range(rows)] for r in range(rows): for c in range(cols): live = sum(board[r + dr][c + dc] for dr in (-1, 0, 1) for dc in (-1, 0, 1) if (dr or dc) and 0 <= r + dr < rows and 0 <= c + dc < cols) out[r][c] = 1 if live == 3 or (board[r][c] and live == 2) else 0 return out b = [[0, 1, 0], [0, 0, 1], [1, 1, 1], [0, 0, 0]]game_of_life(b)assert b == [[0, 0, 0], [1, 0, 1], [0, 1, 1], [0, 1, 0]]blinker = [[0, 0, 0], [1, 1, 1], [0, 0, 0]]game_of_life(blinker)assert blinker == [[0, 1, 0], [0, 1, 0], [0, 1, 0]]import randomrandom.seed(9)for _ in range(200): R, C = random.randint(1, 6), random.randint(1, 6) g = [[random.randint(0, 1) for _ in range(C)] for _ in range(R)] want = copy_version(g) game_of_life(g) assert g == wantprint(blinker)
Output
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.

Quick check
Why must the neighbour count read cell & 1 rather than cell?
Need a nudge? A hint rules out a wrong answer.

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 - c diagonal and its r + c anti-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 - c diagonal 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.
Python
from collections import defaultdict def is_toeplitz(m): """Every top-left to bottom-right diagonal holds one value.""" seen = {} for r, row in enumerate(m): for c, v in enumerate(row): if seen.setdefault(r - c, v) != v: # r - c is constant on a "\" diagonal return False return True def find_diagonal_order(m): """Diagonal Traverse: zigzag along the r + c anti-diagonals.""" groups = defaultdict(list) for r, row in enumerate(m): for c, v in enumerate(row): groups[r + c].append(v) # r + c is constant on a "/" diagonal out = [] for d in range(len(m) + len(m[0]) - 1): # cells were added with r increasing; even diagonals go upwards (r decreasing) out.extend(reversed(groups[d]) if d % 2 == 0 else groups[d]) return out def queens_safe(placed, r, c): """placed: list of (row, col). Can a queen go at (r, c)?""" return all(c != pc and r - c != pr - pc and r + c != pr + pc for pr, pc in placed) assert is_toeplitz([[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]]) is Trueassert is_toeplitz([[1, 2], [2, 2]]) is Falseassert find_diagonal_order([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [1, 2, 4, 7, 5, 3, 6, 8, 9]assert find_diagonal_order([[1, 2], [3, 4]]) == [1, 2, 3, 4]assert queens_safe([(0, 1)], 1, 3) is Trueassert queens_safe([(0, 1)], 1, 2) is False # same "\" diagonal: 0-1 == 1-2assert queens_safe([(0, 1)], 1, 0) is False # same "/" diagonal: 0+1 == 1+0print(find_diagonal_order([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
Output
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.

Staircase search for 5, starting top-right
1471115
2581219
3691622
1013141724
1821232630

Start at 15. It is bigger than 5, and everything below it in column 4 is even bigger. Drop the column: move left.

1/4
Python
def search_matrix(m, target): """Rows sorted, and each row starts after the previous row ends: one sorted list.""" rows, cols = len(m), len(m[0]) lo, hi = 0, rows * cols - 1 while lo <= hi: mid = (lo + hi) // 2 r, c = divmod(mid, cols) # flat index -> cell if m[r][c] == target: return True if m[r][c] < target: lo = mid + 1 else: hi = mid - 1 return False def search_matrix_ii(m, target): """Rows sorted left to right, columns sorted top to bottom. Staircase search.""" r, c = 0, len(m[0]) - 1 # start at the top-right corner steps = 0 while r < len(m) and c >= 0: steps += 1 v = m[r][c] if v == target: return True, steps if v > target: c -= 1 # everything below in this column is bigger else: r += 1 # everything left in this row is smaller return False, steps A = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]]assert search_matrix(A, 3) is Trueassert search_matrix(A, 13) is Falseassert all(search_matrix(A, v) for row in A for v in row) B = [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30],]assert search_matrix_ii(B, 5) == (True, 5)assert search_matrix_ii(B, 20)[0] is Falseassert all(search_matrix_ii(B, v)[0] for row in B for v in row)assert all(search_matrix_ii(B, t)[1] <= len(B) + len(B[0]) - 1 for t in range(0, 32))print(search_matrix_ii(B, 5), search_matrix_ii(B, 20))
Output
Press Run (⌘ Enter) to see what happens.
Quick check
Why does the staircase search start at the top-right corner rather than the top-left?
Need a nudge? A hint rules out a wrong answer.

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.

Python
def is_valid_sudoku(board): rows = [set() for _ in range(9)] cols = [set() for _ in range(9)] boxes = [set() for _ in range(9)] for r in range(9): for c in range(9): v = board[r][c] if v == ".": continue b = (r // 3) * 3 + c // 3 # box number 0..8, row-major if v in rows[r] or v in cols[c] or v in boxes[b]: return False rows[r].add(v) cols[c].add(v) boxes[b].add(v) return True board = [ ["5", "3", ".", ".", "7", ".", ".", ".", "."], ["6", ".", ".", "1", "9", "5", ".", ".", "."], [".", "9", "8", ".", ".", ".", ".", "6", "."], ["8", ".", ".", ".", "6", ".", ".", ".", "3"], ["4", ".", ".", "8", ".", "3", ".", ".", "1"], ["7", ".", ".", ".", "2", ".", ".", ".", "6"], [".", "6", ".", ".", ".", ".", "2", "8", "."], [".", ".", ".", "4", "1", "9", ".", ".", "5"], [".", ".", ".", ".", "8", ".", ".", "7", "9"],]assert is_valid_sudoku(board) is Truebad = [row[:] for row in board]bad[0][0] = "8" # clashes with the 8 in column 0 and box 0assert is_valid_sudoku(bad) is Falsebox_clash = [row[:] for row in board]box_clash[1][1] = "8" # row and column are fine; box 0 already has an 8assert is_valid_sudoku(box_clash) is Falseassert [(r // 3) * 3 + c // 3 for r, c in [(0, 0), (4, 4), (2, 7), (8, 0), (8, 8)]] == [0, 4, 2, 6, 8]print(is_valid_sudoku(board), is_valid_sudoku(box_clash))
Output
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 the pairs0/5 matched

Match each grid task to the key or formula it needs.

Choose an item, then its match on the other side.

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 no grid[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.

Key terms
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).