Diagonal Traverse (LeetCode 498): Solution and Explanation

Medium
Array
Matrix
Simulation

Read every element of an m x n matrix in a zigzag over its anti-diagonals: up and to the right on the first diagonal, down and to the left on the next, alternating until the bottom-right cell, and return the values in that order.

Intuition

The tempting approach is to simulate a bouncing cursor: move up-right, and when you hit the top or right wall, turn and move down-left. It works, but the wall cases (top edge, right edge, the corner where both hit at once) are easy to get wrong.

A cleaner way to see the matrix is by anti-diagonals. Every cell on one diagonal has the same r + c. Call it d. The first diagonal has d = 0, the last has d = m + n - 2, and the direction is simply the parity of d: even diagonals go up-right, odd ones go down-left.

So the only question left is where each diagonal starts. Going up-right, the row decreases, so start at the largest valid row: r = min(d, m - 1). Going down-left, the column decreases, so start at c = min(d, n - 1). From there, walk until the other coordinate leaves the matrix.

This removes the bounce logic entirely. Each diagonal is a short, bounded loop, and every cell is touched once.

Approach: Iterate over diagonal index

  1. Let m and n be the matrix dimensions and create an empty result.
  2. Loop d from 0 to m + n - 2.
  3. If d is even, set r = min(d, m - 1) and, while r >= 0 and d - r < n, append mat[r][d - r] and decrease r.
  4. If d is odd, set c = min(d, n - 1) and, while c >= 0 and d - c < m, append mat[d - c][c] and decrease c.
  5. Return result.

Step-by-step example

mat = [[1,2,3],[4,5,6],[7,8,9]]
  1. d = 0 (even): start at r = 0, read 1. result = [1].
  2. d = 1 (odd): start at c = 1, read (0,1) = 2 then (1,0) = 4. result = [1,2,4].
  3. d = 2 (even): start at r = 2, read (2,0) = 7, (1,1) = 5, (0,2) = 3. result = [1,2,4,7,5,3].
  4. d = 3 (odd): start at c = min(3, 2) = 2, read (1,2) = 6 then (2,1) = 8.
  5. d = 4 (even): start at r = 2, read (2,2) = 9. The answer is [1,2,4,7,5,3,6,8,9].

Code: Python, Java, C++

1class Solution:
2    def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
3        m, n = len(mat), len(mat[0])
4        result = []
5        for d in range(m + n - 1):
6            if d % 2 == 0:
7                r = min(d, m - 1)
8                while r >= 0 and d - r < n:
9                    result.append(mat[r][d - r])
10                    r -= 1
11            else:
12                c = min(d, n - 1)
13                while c >= 0 and d - c < m:
14                    result.append(mat[d - c][c])
15                    c -= 1
16        return result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m * n)

Each cell belongs to exactly one diagonal and is appended once. The loop over diagonals adds only m + n - 1 iterations of overhead.

Space

O(1)

Apart from the output array, only a few index variables are used.

Other approaches

Simulate the bouncing cursor (time O(m * n), space O(1))

Keep a current cell and direction, step diagonally, and change direction when the next step would leave the matrix, moving right or down depending on which wall was hit. It is the same complexity but has more edge cases to handle.

Group by r + c, then reverse (time O(m * n), space O(m * n))

Collect every cell into a bucket keyed by r + c while scanning row by row, then output the buckets in order, reversing the even ones. Simple to write, but it stores a second copy of the matrix.

Common mistakes

  • Starting every diagonal at row 0 or column 0. Once d passes m - 1 or n - 1 the starting cell must be clamped to the last row or column.
  • Mixing up the directions. The first diagonal after the single top-left cell goes down-left, so even d means up-right.
  • Assuming a square matrix. A 1 x n or m x 1 matrix must still work, with each diagonal holding a single cell.
  • In the bouncing simulation, checking the top wall before the right wall at the top-right corner, which sends the cursor out of bounds.

Frequently asked questions

Why do cells on one diagonal share r + c?

Moving up-right decreases r by one and increases c by one, so their sum stays constant along the whole diagonal.

How many diagonals does an m x n matrix have?

m + n - 1. The sum r + c ranges from 0 at the top-left to (m - 1) + (n - 1) at the bottom-right.

Does Diagonal Traverse need extra memory?

Only for the output array. The diagonal-index loop computes each starting cell directly, so no buckets or visited markers are needed.

What is the time complexity of Diagonal Traverse?

O(m * n), because each of the m * n cells is read exactly once.