Matrix and 2D Array Coding Interview: Patterns That Hold

A decision procedure for matrix and 2D array coding interview questions: name the shape, state your index convention, classify into one of four patterns, then trace a 3×3 before coding.

By AI Interview AssistantPublished 9 min read

In a matrix and 2D array coding interview, treat the input as a grid with a shape you state out loud and a traversal order you choose deliberately. Then classify the question into one of four patterns: row or column scan, boundary spiral, in-place rotation, or grid search with visited marks. Before you write a loop, say the number of rows and columns, the index convention, and whether the grid is square or ragged. Most index bugs come from skipping that step, not from the algorithm itself.

Say the shape and index convention first

Open every matrix question with the same three facts. Rows are len(grid) and columns are len(grid[0]). The grid is square, rectangular or ragged. And grid[r][c] means row r, column c, with r growing downward.

That last sentence sounds trivial until you are three loops deep and cannot remember whether your outer loop walks rows or columns. Saying it once fixes the convention for both of you.

Ragged input changes every bound check. If rows can have different lengths, len(grid[0]) is a lie and you need len(grid[r]) inside the row loop. Ask before you assume.

Guard the empty case before you read grid[0]. Writing cols = len(grid[0]) on an empty list raises an IndexError, and a candidate who crashes on [] in the first ten seconds has spent credibility on a problem they can solve.

if not grid or not grid[0]:
    return []
rows, cols = len(grid), len(grid[0])

Four patterns that cover most matrix questions

PatternWhen it fitsTimeExtra space
Row/column scanSearch or count in a sorted or uniform gridO(rows × cols)O(1)
Boundary spiralOutput order follows the edges inwardO(rows × cols)O(1) beyond output
In-place rotation90° turn of a square matrix, no copy allowedO(n²)O(1)
Grid search with visitedReachability, shortest steps, connected regionsO(rows × cols)O(rows × cols)

Each pattern has a different failure mode. The scan fails when you assume sortedness you never checked. The spiral fails on the last row or column. Rotation fails if the matrix is not square. Grid search fails when you forget the visited set and revisit cells forever.

For the grid search pattern, the choice of BFS or DFS matters less than the bounds check before you enqueue. If you want to reason about that choice properly, read how to choose a traversal for grid search.

Worked example: rotate a square matrix 90° clockwise

Input: [[1,2,3],[4,5,6],[7,8,9]]. Expected output: [[7,4,1],[8,5,2],[9,6,3]].

The trick is two steps. Transpose, then reverse each row.

def rotate(matrix):
    n = len(matrix)
    # Step 1: transpose. Swap grid[r][c] with grid[c][r] for c > r.
    for r in range(n):
        for c in range(r + 1, n):
            matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c]
    # Step 2: reverse each row.
    for row in matrix:
        row.reverse()
    return matrix

Trace it. After the transpose, the grid is [[1,4,7],[2,5,8],[3,6,9]]. Reversing each row gives [[7,4,1],[8,5,2],[9,6,3]]. That is the expected output.

The inner loop starts at c = r + 1 because the diagonal does not move and each off-diagonal pair should be swapped exactly once. Starting at c = 0 would swap every pair twice and put you back where you began.

Complexity: O(n²) time, because you touch each of the n² cells a constant number of times. O(1) extra space, because the swaps happen in place.

This works only on a square matrix. A rectangular grid cannot be rotated in place because the output has a different shape. Say that out loud when it applies.

Worked example: spiral order with shrinking bounds

On the same input, spiral order is [1,2,3,6,9,8,7,4,5]. Walk the top edge left to right, the right edge top to bottom, the bottom edge right to left, then the left edge bottom to top, shrinking after each.

def spiral_order(matrix):
    if not matrix or not matrix[0]:
        return []
    res = []
    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):
            res.append(matrix[top][c])
        top += 1
        for r in range(top, bottom + 1):
            res.append(matrix[r][right])
        right -= 1
        if top <= bottom:
            for c in range(right, left - 1, -1):
                res.append(matrix[bottom][c])
            bottom -= 1
        if left <= right:
            for r in range(bottom, top - 1, -1):
                res.append(matrix[r][left])
            left += 1
    return res

The two if guards are the part people skip. Without them, a grid with a single remaining row prints that row twice, once as the top edge and once as the bottom. The same happens to a single remaining column.

Complexity: O(rows × cols) time, because each cell is appended once. O(1) extra space beyond the output list.

A one-line classification you can say out loud

The point of classification is that it compresses the problem into a sentence you can defend. Here is the shape of that sentence:

This is a boundary spiral on a rectangular grid, O(rows × cols) time, O(1) extra space.

Swap the pattern and the complexity for the question in front of you. "This is an in-place rotation on a square matrix, O(n²) time, O(1) extra space." "This is a grid search with visited marks on a rectangular grid, O(rows × cols) time, O(rows × cols) extra space."

Saying it before you code does two things. It gives the interviewer a chance to correct a wrong assumption early, and it forces you to commit to a complexity you can then check against your loop. If the sentence feels shaky, you have not classified yet.

Shape questions to ask before you write a loop

Ask these four questions, in this order, every time:

  • Square or rectangular? Square unlocks in-place rotation. Rectangular rules it out.
  • Can the input be empty? If yes, guard before reading grid[0].
  • Are the values sorted along rows or columns? Sortedness unlocks a scan that skips cells; unsorted input does not.
  • Am I allowed to mutate the input? If not, copy the row or column you need before overwriting it.

Each question removes a class of bugs before you write a line. The mutation question matters most: writing into a cell you still need to read is the quietest way to produce a wrong answer that looks right on the small example.

For a broader pass over boundary conditions, see find and explain matrix edge cases.

Where matrix loops go wrong under time pressure

Three failures account for most broken matrix code in a live screen.

Off-by-one on the last row or column. You write range(top, bottom) and lose the bottom edge. The fix is to name the bound as a variable and check it in your trace: does the loop include bottom? If you cannot answer from the code, the code is unclear.

Mutating the grid while reading it. In a problem like set-matrix-zeroes, writing a zero into a cell you later read as data spreads the zero across the whole grid. The fix is to record what you need first, then write.

Forgetting the visited set in grid search. Without it, two adjacent cells enqueue each other forever. Mark on enqueue, not on dequeue, so a cell is never added twice. Marking on dequeue lets duplicates into the queue and doubles your work.

If you want to practise narrating these fixes, talk through array solutions without freezing covers the same reasoning on one-dimensional inputs.

The one rule: classify before you code

Name the pattern, the shape and the complexity in one sentence, then code. If you cannot name the pattern, trace a 2×2 example until you can. That single habit turns a matrix question from a memory test into a decision you can explain.

For practice, take three problems per pattern and work them out loud, timing only the classification step. Under a minute, every time, and the loops get easier to write.

Frequently asked questions

What if the matrix is rectangular rather than square — can I still rotate it in place?

No. A 90° rotation turns an m × n grid into an n × m grid, so the output cannot occupy the same memory shape. Allocate a new grid and fill it with result[c][m - 1 - r] = grid[r][c]. Say this trade-off out loud: you accept O(m × n) extra space because in-place is geometrically impossible.

How do I handle a matrix stored as a list of strings instead of a list of lists?

Index it the same way, because strings support grid[r][c] and len(grid[r]). The difference is mutation: strings are immutable, so you cannot write into a cell. Build a list of lists first if the solution needs to modify the grid, and mention that conversion and its O(rows × cols) cost before you start.

Should I use BFS or DFS for grid search questions?

Use BFS when you need the shortest number of steps, because it reaches cells in order of distance. Use DFS when you only need reachability or connected regions and want simpler code. Both are O(rows × cols) time; BFS can hold more in the queue at once, so mention that if space matters.

How much time should I spend tracing before I start coding?

Aim for under a minute on a 2×2 or 3×3 example. Trace the loop bounds and the stopping condition, not every cell. If the trace takes longer, your loop is doing too much and should be split. A short trace that catches an off-by-one is cheaper than a rewrite after the code fails.

Practising matrix questions out loud? See how AI Interview assistant works.

  • Matrix and 2d array coding interview
  • Coding interview
  • Data structures and algorithms
  • Technical interview preparation
A developer sorting numbered index cards into order on a desk beside a laptop while explaining out loud, with a notebook of arrows nearby

12 min read

Sorting Coding Interview: Reason Through the Algorithm Out Loud

A sorting coding interview tests how you choose and defend an approach, not how well you memorised quicksort. Learn a constraint-first decision process and a narration pattern you can rehearse.

  • Sorting coding interview
  • Sorting interview questions
A hand picking the largest coin from a pile of mixed coins on a table to fill a small tray

14 min read

Greedy Algorithms Coding Interview: Justify the Choice

A practical script for greedy algorithms coding interview questions: state the choice, justify it, test a counterexample, and explain the complexity without rambling.

  • Greedy algorithms coding interview
  • Greedy algorithms interview questions