LeetCode #498 Medium

Diagonal Traverse

Diagonal Traverse is LeetCode 498 (Medium). Given an m × n matrix mat, return all of its values in zigzag diagonal order. Start at the top-left cell, read the first diagonal going up and to the right, the next one going down and to the left, and keep alternating until the bottom-right cell.

  • The matrix need not be square, and it can be a single row or a single column.
  • It holds at most 10⁴ cells, so visiting each cell a constant number of times is plenty.
Constraints
  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 10⁴
  • 1 <= m * n <= 10⁴
  • -10⁵ <= mat[i][j] <= 10⁵
matrixsimulationarrays
Open on LeetCode ↗
02

Intuition

Every cell on one of these diagonals has the same row + col. Moving up-right takes 1 off the row and adds 1 to the column, so the sum stays put. The sums run from 0 at the top-left to m + n − 2 at the bottom-right, one per diagonal.

So drop each cell into bucket number row + col. Scanning the matrix row by row fills every bucket from top to bottom, which is the down-left direction. The zigzag starts upward on diagonal 0, so reverse the even buckets, keep the odd ones, and join them in order.

How to spot this pattern

This works for any diagonal traversal of a matrix: cells on one anti-diagonal share row + col, and cells on one main diagonal share row − col. Group cells by that number and the walking turns into list work.

03

Approach

Try it first

Before reading on, write row + col inside each cell of a 3 × 3 grid and look at which cells share a number. Then decide which of those groups must be read backwards. Aim for O(m · n) time.

1

Make one bucket per diagonal

The sum row + col takes m + n − 1 values, from 0 to m + n − 2, so create that many empty lists. Every cell belongs to exactly one bucket, so no value is read twice or skipped.

2

Fill the buckets in row order

Scan the rows top to bottom and append mat[r][c] to bucket r + c. Each bucket receives its cells in increasing row order, so it already reads from its top-right end to its bottom-left end, the down-left direction.

3

Reverse every even diagonal

Diagonal 0 goes up, diagonal 1 goes down, and the directions keep alternating, so the even diagonals are the upward ones. Reverse those buckets so they start at the bottom-left, and leave the odd ones as they are.

4

Join the buckets in order

Extend the answer with bucket 0, then bucket 1, and so on. Each diagonal ends next to where the following one begins, so the joined list is the zigzag path the problem asks for.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def findDiagonalOrder(self, mat):
▶3 m, n = len(mat), len(mat[0])
▶4 diags = [[] for _ in range(m + n - 1)]
▶5 for r in range(m):
▶6 for c in range(n):
▶7 diags[r + c].append(mat[r][c])
▶8 result = []
▶9 for d in range(m + n - 1):
▶10 if d % 2 == 0:
▶11 diags[d].reverse()
▶12 result.extend(diags[d])
▶13 return result
matrixbucket row + colcol 0col 1col 212345678901201122334answerrow 0: 1, 2, 3 go to buckets 0, 1, 2
row0
Each cell goes to the bucket numbered by its row plus its column. Moving up-right along a diagonal takes one off the row and adds one to the column, so every cell on one diagonal lands in the same bucket.
matrixbucket row + colcol 0col 1col 212345678901201124235364answerrow 1: 4, 5, 6 go to buckets 1, 2, 3
row1
Row 1 adds one cell to each of buckets 1 to 3. Rows are scanned top to bottom, so every bucket keeps its cells in top-to-bottom order, which is the down-left direction.
matrixbucket row + colcol 0col 1col 212345678901201124235736849answerrow 2: 7, 8, 9 go to buckets 2, 3, 4
row2
Row 2 adds one cell to each of buckets 2 to 4. Rows are scanned top to bottom, so every bucket keeps its cells in top-to-bottom order, which is the down-left direction.
matrixbucket row + colcol 0col 1col 212345678901201124235736849answer1diagonal 0 has one cell → answer gets 1
diagonal0
directionup
answer so far1 of 9
The zigzag starts upward on diagonal 0 and alternates, so even diagonals go up. The bucket was filled top to bottom, so it is reversed before its cells join the answer; with one cell, the direction makes no difference.
matrixbucket row + colcol 0col 1col 212345678901201124235736849answer124diagonal 1 is odd → kept, going down: 2, 4
diagonal1
directiondown
answer so far3 of 9
Odd diagonals go down, which is exactly the top-to-bottom order the bucket was filled in, so it is used as it is.
matrixbucket row + colcol 0col 1col 2123456789012011242753reversed36849answer124753diagonal 2 is even → reversed to go up: 7, 5, 3
diagonal2
directionup
answer so far6 of 9
The zigzag starts upward on diagonal 0 and alternates, so even diagonals go up. The bucket was filled top to bottom, so it is reversed before its cells join the answer.
matrixbucket row + colcol 0col 1col 2123456789012011242753reversed36849answer12475368diagonal 3 is odd → kept, going down: 6, 8
diagonal3
directiondown
answer so far8 of 9
Odd diagonals go down, which is exactly the top-to-bottom order the bucket was filled in, so it is used as it is.
matrixbucket row + colcol 0col 1col 2123456789012011242753reversed36849answer124753689diagonal 4 has one cell → answer gets 9
diagonal4
directionup
answer so far9 of 9
The zigzag starts upward on diagonal 0 and alternates, so even diagonals go up. The bucket was filled top to bottom, so it is reversed before its cells join the answer; with one cell, the direction makes no difference.
matrixbucket row + colcol 0col 1col 2123456789012011242753reversed36849answer124753689answer: 1, 2, 4, 7, 5, 3, 6, 8, 9
answer[1, 2, 4, 7, 5, 3, 6, 8, 9]
All 5 buckets are joined in order. Each diagonal ends next to where the following one begins, so the list reads as one continuous zigzag through all 9 cells.
05

Common pitfalls

Reversing the odd diagonals

✗ Wrong
if d % 2 == 1:
✓ Right
if d % 2 == 0:

Row order fills every bucket going down-left, and diagonal 0 must go up, so the even buckets are the ones to flip. On [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the wrong parity returns [1, 4, 2, 3, 5, 7, 8, 6, 9] instead of [1, 2, 4, 7, 5, 3, 6, 8, 9].

Grouping by row − col

✗ Wrong
diags[r - c].append(mat[r][c])
✓ Right
diags[r + c].append(mat[r][c])

r − c is constant along the other kind of diagonal, top-left to bottom-right, and it goes negative, which Python quietly treats as counting from the end of the list. On [[1, 2], [3, 4]] it returns [4, 1, 3, 2] instead of [1, 2, 3, 4].

06

Edge cases

A single column, e.g. [[1], [2], [3]]

Every bucket holds one cell, so reversing changes nothing and the answer is the column read top to bottom. A single row works the same way.

A wide matrix, e.g. 2 × 4

The middle diagonals are cut short by the top and bottom rows and never touch the left edge. Bucketing by row + col needs no rule for where a diagonal starts or ends, so these shapes need no extra code.

07

Complexity

Time
O(m · n)
Space
O(m · n)
Each cell is appended to a bucket once and copied into the answer once. The buckets together hold every value, the same size as the answer itself.
08

Diagonal Traverse FAQ

Can it be done without the buckets?

Yes. Diagonal d has its top-right end at row 0, column d while d < n, and at row d − n + 1, column n − 1 after that. Step row + 1, col − 1 from there until you leave the grid, and append that run backwards when d is even. Beyond the answer, this needs only one diagonal's worth of memory.

Why do cell-by-cell walks break at the corners?

Many solutions move one cell at a time with an up or down flag, and at a wall step along it and flip the flag. The order of the wall checks matters. Moving up from the top-right cell, the walker is on the top row and the last column at once; testing "top row, so step right" first sends it off the grid, so "last column, so step down" must be tested first.