Skip to content
Problem 498 · LeetCode 498(opens in a new tab)

Diagonal Traverse

MediumArrays

You are given a matrix mat with m rows and n columns. Read every value in a zigzag along the anti-diagonals (the lines where row + column is constant) and return them in that order.

Start at the top-left cell and move up and to the right. When you hit the edge, step to the next diagonal and come back down and to the left. Keep switching direction on each new diagonal until every cell has been read.

Example 1

Input:  mat = [[3, 8, 1], [6, 2, 7]]
Output: [3, 8, 6, 2, 1, 7]
Why:    diagonals 3 | 8 6 | 2 1 | 7, zigzagging
2 more examples and the constraints

Example 2

Input:  mat = [[5, 1, 9], [3, 8, 2], [7, 4, 6]]
Output: [5, 1, 3, 7, 8, 9, 2, 4, 6]
Why:    the middle diagonal 7, 8, 9 is read going up

Example 3

Input:  mat = [[4], [0], [-2]]
Output: [4, 0, -2]
Why:    one column: every diagonal is a single cell

Constraints

  • 1 ≤ m, n ≤ 10,000
  • 1 ≤ m × n ≤ 10,000
  • −100,000 ≤ mat[r][c] ≤ 100,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Group by diagonalO(m·n)
  2. Walk and bounceO(m·n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 cellsVerdict
Group by diagonalO(m·n)
Passes; extra copy of the data
Walk and bounceO(m·n)
Best; one pass, no extra lists

m = rows, n = columns.

Edge cases to test

  • One cell. [[9]] gives [9].
  • One row. Every move up-right is blocked by the top, so you step right each time: the row comes back as is.
  • One column. Every move bounces down: the column comes back top to bottom.
  • Wide or tall matrix. Diagonals hit the top and bottom edges or the left and right ones; both bounce rules are needed.

Common mistakes

  • Checking the top row before the last column, which walks off the matrix at the top-right corner.
  • Reversing the odd diagonals instead of the even ones, which starts the zigzag going down.
  • Assuming a square matrix and mixing up m and n.

How to talk through it

  1. 1Clarify. Can the matrix be a single row or column? Which direction does the first diagonal go?
  2. 2Name the invariant. All cells on one anti-diagonal share r + c; its parity gives the direction.
  3. 3Give the simple version. Bucket by r + c, reverse the even buckets, join. O(m·n) time and space.
  4. 4Code the walk. Move diagonally; at an edge slide along it. Explain the corner order.
  5. 5Test out loud. Run a single row, a single column, and a 2 × 3 matrix by hand.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?