Diagonal Traverse - Problem
Given an m x n matrix mat, return an array of all the elements of the matrix traversed in diagonal order.
The diagonal traversal follows a zigzag pattern: starting from the top-left corner, move diagonally up-right, then when hitting a boundary, move to the next diagonal and go down-left, alternating this pattern until all elements are visited.
Example: For matrix [[1,2,3],[4,5,6],[7,8,9]], the diagonal order is [1,2,4,7,5,3,6,8,9].
Input & Output
Example 1 — Basic 3x3 Matrix
$
Input:
mat = [[1,2,3],[4,5,6],[7,8,9]]
›
Output:
[1,2,4,7,5,3,6,8,9]
💡 Note:
Start at (0,0)=1, move up-right to (0,1)=2, hit top boundary so switch to down-left: (1,0)=4, hit left boundary so switch to up-right: (2,0)=7, (1,1)=5, (0,2)=3, and so on following the diagonal zigzag pattern.
Example 2 — Rectangular Matrix
$
Input:
mat = [[1,2],[3,4]]
›
Output:
[1,2,3,4]
💡 Note:
Start at (0,0)=1, move to (0,1)=2, hit right boundary so move down to (1,0)=3, then to (1,1)=4. The diagonal pattern handles rectangular matrices correctly.
Example 3 — Single Row
$
Input:
mat = [[1,2,3,4]]
›
Output:
[1,2,3,4]
💡 Note:
With only one row, we traverse left to right since each element forms its own diagonal.
Constraints
- m == mat.length
- n == mat[i].length
- 1 ≤ m, n ≤ 104
- 1 ≤ m * n ≤ 104
- -105 ≤ mat[i][j] ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input Matrix
3x3 matrix with elements 1-9
2
Diagonal Pattern
Follow diagonals, alternating up-right and down-left
3
Output Array
Elements collected in diagonal order
Key Takeaway
🎯 Key Insight: Track diagonal direction and handle boundary conditions to simulate the zigzag traversal pattern efficiently
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code