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
Diagonal Traverse - Direct Simulation INPUT m x n Matrix (3x3) 1 2 3 4 5 6 7 8 9 Red: Up-Right direction Green: Down-Left direction Input Array: [[1,2,3],[4,5,6],[7,8,9]] rows=3, cols=3 Total diagonals: 5 ALGORITHM STEPS 1 Initialize Start at (0,0), dir=up-right 2 Traverse Diagonal Move along current diagonal 3 Handle Boundary Switch direction at edges 4 Repeat Until Done Visit all m*n elements Direction Rules: Up-Right: row--, col++ Down-Left: row++, col-- At top/right boundary: switch to down-left At bottom/left boundary: switch to up-right FINAL RESULT Traversal Order: 1 (1st) 2 (2nd) 3 (6th) 4 (3rd) 5 (5th) 6 (7th) 7 (4th) 8 (8th) 9 (9th) Output Array: [1,2,4,7,5,3,6,8,9] OK - Complete! 9 elements visited 5 diagonal traversals Key Insight: Direct simulation tracks position (row, col) and direction flag. For an m x n matrix, there are (m + n - 1) diagonals. Alternate between up-right (row-1, col+1) and down-left (row+1, col-1). Time: O(m*n) - visit each element once. Space: O(1) excluding output array. TutorialsPoint - Diagonal Traverse | Direct Simulation Approach
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
78.0K Views
Medium Frequency
~15 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen