15% off all plans & roadmaps Use code

See plans

Diagonal Traverse

Updated

TL;DR: Diagonal Traverse asks you to read a matrix along its anti-diagonals, reversing direction on each one. The winning idea is one pass that tracks a row, a column and a direction, with boundary checks that decide each move.

Problem

Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order. The order zigzags: each diagonal runs in the opposite direction from the one before it.

Example 1

Input: mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output: [1, 2, 4, 7, 5, 3, 6, 8, 9]

Constraints

  • The total number of elements of the matrix will not exceed 10,000.

Constraints that matter

  • The matrix holds at most 10,000 cells, so a pass over all cells is cheap. Rescanning the matrix once per diagonal multiplies that cost by M + N - 1 and wastes most of the work.
  • Because the matrix can be non-square, the code must use M for rows and N for columns everywhere. A 1 x N or M x 1 matrix is valid input and must still produce every element.
  • The output must hold every element exactly once, so any approach that skips or repeats a cell is wrong even when the order looks right.

View on LeetCode

Hints

Hint 1

Every cell on one diagonal shares the same index sum, i + j.

Hint 2

A beginner usually asks, for each diagonal, which cells belong to it.

Solution

Intuition

Every cell on one diagonal shares the same index sum, i + j. The output lists the diagonals in order of that sum, from 0 to M + N - 2. Odd sums keep their top-to-bottom order and even sums reverse it, which produces the zigzag. Grouping cells by their index sum is the first useful idea.

Picture a ball rolling across a pool table, one cell per tick. The ball's row and column are the only state, and the walls alone decide when it turns.

This is also a simulation problem. You walk the matrix one cell at a time and keep a small state: the current row, the current column and a direction flag. Boundary checks decide each move. The walk changes direction only when it reaches a wall, so the checks only need to handle the walls.

Why the walk works: a diagonal going up-right ends on the top or right edge. A diagonal going down-left ends on the bottom or left edge. At each edge there is exactly one valid next cell in the new direction, and the walk takes it. Every step lands on a new valid cell, so the walk visits each cell once.

Watch the pattern animation

Worked example

Input: mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output: [1, 2, 4, 7, 5, 3, 6, 8, 9]
Explanation: The walk starts at 1 and moves up-right to 2 and then down-left to 4. At the left wall it steps down to 7, then climbs up-right through 5 and 3. It turns at the top-right corner, goes down-left through 6 and 8, and ends at 9.

Approach 1: Brute force: rescan the matrix for each diagonal

A beginner usually asks, for each diagonal, which cells belong to it. For diagonal d, check every cell (i, j) and keep the ones where i + j equals d. Reverse the list for even d, then append it to the answer.

This is correct, but it is wasteful. Each diagonal costs a full scan of the matrix, even though most cells belong to some other diagonal. With M + N - 1 diagonals, the same cells are read again and again.

Steps

  1. Read M and N from the matrix, and create an empty result list.
  2. For each diagonal sum d from 0 to M + N - 2, create an empty list named diagonal.
  3. Scan every cell (i, j). If i + j equals d, append mat[i][j] to diagonal.
  4. If d is even, reverse diagonal so it runs up-right.
  5. Append every value in diagonal to the result and move to the next d.

Dry run

Take the example with M = 3 and N = 3. For d = 0, the scan finds only (0, 0) = 1, so the list is [1]. For d = 1, the scan finds (0, 1) = 2 and (1, 0) = 4 in row order, giving [2, 4]. Since 1 is odd, the list stays as it is.

For d = 2, the scan finds (0, 2) = 3, (1, 1) = 5 and (2, 0) = 7, giving [3, 5, 7]. Since 2 is even, the list reverses to [7, 5, 3].

For d = 3, the list is [6, 8]. For d = 4, the list is [9]. Concatenating the lists gives 1, 2, 4, 7, 5, 3, 6, 8, 9, which matches the expected output.

Complexity

TimeO((M + N) * M * N)
SpaceO(min(M, N)) auxiliary, not counting the output

Let n be the number of cells, M * N. There are M + N - 1 diagonals, and each one triggers a full double loop over all M * N cells, so the scans cost (M + N - 1) * M * N. The list for one diagonal holds at most min(M, N) values, and only one list exists at a time, so the auxiliary space is O(min(M, N)).

PythonTested in our runner

class Solution:
    def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
        if not mat or not mat[0]:
            return []
        m, n = len(mat), len(mat[0])
        result = []
        for d in range(m + n - 1):
            diagonal = []
            # Rescan the whole matrix to find cells with i + j == d
            for i in range(m):
                for j in range(n):
                    if i + j == d:
                        diagonal.append(mat[i][j])
            if d % 2 == 0:
                diagonal.reverse()
            result.extend(diagonal)
        return result

Approach 2: Bucket cells by index sum

What's slow: the brute force scans all M * N cells once for every diagonal. Most of those reads only skip cells that belong elsewhere.

The insight that fixes it: a cell's diagonal is known the moment you see it, because the diagonal is i + j. Read the matrix once and drop each value into a bucket indexed by its sum. The buckets come out grouped by diagonal, so the only remaining work is reversing the even buckets.

Steps

  1. Create M + N - 1 empty buckets, one for each index sum.
  2. Scan every cell once and append mat[i][j] to bucket i + j.
  3. For each bucket in order, reverse it if its index is even.
  4. Append each bucket's values to the result in order.

Dry run

Take the example. After the scan, the buckets hold: bucket 0 = [1], bucket 1 = [2, 4], bucket 2 = [3, 5, 7], bucket 3 = [6, 8], bucket 4 = [9]. The scan visits each cell once, so the buckets are built in 9 steps.

Now reverse the even buckets. Bucket 0 stays [1]. Bucket 2 becomes [7, 5, 3]. Bucket 4 stays [9].

The odd buckets stay as they are. Concatenating in order gives 1, 2, 4, 7, 5, 3, 6, 8, 9.

Complexity

TimeO(M * N)
SpaceO(M * N) auxiliary for the buckets, plus the output

Let n be M * N. The scan appends each cell once, which is n appends. The reversal pass touches each stored value at most once more, which adds at most n steps. The total work is O(n).

The buckets hold every value before the output is built, so the auxiliary space is O(n).

PythonTested in our runner

class Solution:
    def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
        if not mat or not mat[0]:
            return []
        m, n = len(mat), len(mat[0])
        buckets = [[] for _ in range(m + n - 1)]
        for i in range(m):
            for j in range(n):
                # Every cell on diagonal i + j goes into the same bucket
                buckets[i + j].append(mat[i][j])
        result = []
        for d, diagonal in enumerate(buckets):
            if d % 2 == 0:
                diagonal.reverse()
            result.extend(diagonal)
        return result

The Set Matrix Zeroes (In-place Marking) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Set Matrix Zeroes (In-place Marking)

Part of Array/Matrix Manipulation Patterns

Approach 3: One-pass direction simulationOptimalSet Matrix Zeroes (In-place Marking)

What's slow: the bucket method stores every value in extra lists before it builds the answer. It also reads the whole matrix before it writes anything.

The insight that fixes it: the next cell is always predictable. Keep one position and one direction flag. Emit the current cell, then move one step along the zigzag. Walls change the move.

In the up-right phase, at a right wall go down, and at a top wall go right. In the down-left phase, at a bottom wall go right, and at a left wall go down. Check the right wall before the top wall, and the bottom wall before the left wall, so corners take the move that stays inside the grid.

Steps

  1. Set row = 0, col = 0 and goingUp = true. Create an empty result of size M * N.
  2. Repeat M * N times: append mat[row][col] to the result.
  3. If goingUp: when col == N - 1, move down and set goingUp = false. Otherwise, when row == 0, move right and set goingUp = false. Otherwise, move up-right.
  4. If not goingUp: when row == M - 1, move right and set goingUp = true. Otherwise, when col == 0, move down and set goingUp = true. Otherwise, move down-left.
  5. After the loop, return the result.

Dry run

The table below traces the example. Each row shows the cell appended, the direction it was taken in, which rule fired and the position after the move.

StepCell appendedDirectionRule that firesNext (row, col)
1mat[0][0] = 1uprow is 0, so move right(0, 1), down
2mat[0][1] = 2downneither wall, so down-left(1, 0), down
3mat[1][0] = 4downcol is 0, so move down(2, 0), up
4mat[2][0] = 7upneither wall, so up-right(1, 1), up
5mat[1][1] = 5upneither wall, so up-right(0, 2), up
6mat[0][2] = 3upcol is N - 1, so move down(1, 2), down
7mat[1][2] = 6downneither wall, so down-left(2, 1), down
8mat[2][1] = 8downrow is M - 1, so move right(2, 2), up
9mat[2][2] = 9uploop count reachedstop

The result is 1, 2, 4, 7, 5, 3, 6, 8, 9. The move after step 9 points outside the grid, but the loop ends there and the position is never read again.

Complexity

TimeO(M * N)
SpaceO(1) auxiliary, not counting the output

Let n be M * N. The loop runs exactly n times, and each iteration does a fixed number of comparisons and index updates, so the time is O(n). The only state is the row, the column and one flag, which is a constant amount of memory apart from the output array.

PythonTested in our runner

class Solution:
    def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
        if not mat or not mat[0]:
            return []
        m, n = len(mat), len(mat[0])
        result = []
        row, col = 0, 0
        going_up = True
        for _ in range(m * n):
            result.append(mat[row][col])
            if going_up:
                # Check the right wall before the top wall so the corner turns down
                if col == n - 1:
                    row += 1
                    going_up = False
                elif row == 0:
                    col += 1
                    going_up = False
                else:
                    row -= 1
                    col += 1
            else:
                # Check the bottom wall before the left wall so the corner turns right
                if row == m - 1:
                    col += 1
                    going_up = True
                elif col == 0:
                    row += 1
                    going_up = True
                else:
                    row += 1
                    col -= 1
        return result

Common mistakes

  • if row == 0 tested before if col == n - 1 in the up-right phase. At the top-right corner both are true, and moving right leaves the grid. Test the right wall first so the corner turns down.
  • if d % 2 == 1 in the brute force or bucket version. That reverses the wrong diagonals. Even sums run up-right, so reverse when d % 2 == 0.
  • m = len(mat[0]) and n = len(mat). The labels are swapped, and non-square input then fails with an index error. M is the row count and N is the column count.
  • Forgetting to set goingUp in a wall branch. The walk keeps its old direction after the turn and emits the diagonal in the wrong order. Every wall move must flip the flag.
  • Creating only M or N buckets instead of M + N - 1. The last diagonal has index M + N - 2, so the bucket index goes out of range on any matrix larger than one row or column.

Edge cases

  • A 1 x 1 matrix [[5]] returns [5]. The first move hits both walls, and the loop still runs once.
  • A single row [[1, 2, 3]] returns [1, 2, 3]. The walk turns at the top and bottom wall at every step.
  • A single column [[1], [2], [3]] returns [1, 2, 3]. The walk turns at the left and right walls.
  • A non-square matrix [[1, 2, 3], [4, 5, 6]] returns [1, 2, 4, 5, 3, 6]. Check that M and N are read in the right order.
  • An empty matrix [] returns []. The guard clause must run before any index is read.
  • A 100 x 100 matrix with all values distinct checks the largest allowed shape. Every value must appear once, and the one-pass version stays within O(1) extra space.

Follow-ups interviewers ask

Can you do it with O(1) extra space?
Yes, the one-pass simulation uses only a row, a column and a flag beyond the output array. The output itself must exist, so the total space is still O(M * N) if you count it. Auxiliary space is O(1).
What if you need the traversal to start going down-left instead?
Flip the parity test and the starting direction. Start with goingUp = false in the simulation, or reverse the buckets when the index is odd. Either change keeps the same O(M * N) time.
What if the matrix is too large to fit in memory?
Process the matrix in blocks of rows and keep the current diagonal's partial state between blocks. The simulation only touches one cell at a time, so it works well with a streaming reader. The bucket method would need the whole diagonal set in memory, so it does not fit this case.

Diagonal Traverse FAQ

What is the time complexity of Diagonal Traverse?

The optimal simulation runs in O(M * N) time, because it visits each cell exactly once. The brute force that rescans the matrix per diagonal costs O((M + N) * M * N). The bucket approach is also O(M * N).

Why use direction simulation for Diagonal Traverse?

The walk always takes one of two diagonal moves, and walls decide when it turns. Tracking the row, the column and a direction flag gives the next cell in constant time. The approach avoids storing any diagonal lists.

Can Diagonal Traverse be solved in O(1) extra space?

Yes, if you do not count the output array. The simulation keeps only a row, a column and a flag. Buckets or per-diagonal lists would need O(M * N) or O(min(M, N)) extra space, so they are not O(1).

Why do even diagonals get reversed?

A diagonal with an even index sum runs up-right in the zigzag. Reading the matrix top to bottom gives down-left order, so the list must be reversed. Odd sums already run down-left, so they stay as they are.

Why does the simulation check the right wall before the top wall?

At the top-right corner, both walls are hit at once. Moving right would leave the matrix, so the walk must go down instead. The down-left phase applies the same rule with the bottom wall first.

Asked at

See which companies ask this — Pro

Practise it