Diagonal Traverse - Problem
Matrix Diagonal Traversal

Given an m x n matrix, you need to traverse all elements in a diagonal pattern and return them as a single array. The traversal follows a unique zigzag pattern:

• Start from the top-left corner (0,0)
• Move diagonally up-right, then down-left, then up-right again
• When you hit a boundary, change direction and move to the next diagonal
• Continue until all elements are visited

Example: For matrix [[1,2,3],[4,5,6],[7,8,9]], the diagonal traversal would be [1,2,4,7,5,3,6,8,9]

This problem tests your ability to simulate movement patterns and handle boundary conditions in 2D matrices.

Input & Output

example_1.py — 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: Starting from (0,0), we move diagonally up-right to collect 1,2, then hit boundary and move down-left for 4, then up-right for 7,5,3, and so on following the zigzag pattern.
example_2.py — Rectangular Matrix
$ Input: mat = [[1,2],[3,4]]
Output: [1,2,3,4]
💡 Note: For a 2x2 matrix: start with 1, move up-right to 2, then down-left to 3, finally to 4. The diagonal pattern creates the sequence [1,2,3,4].
example_3.py — Single Row Edge Case
$ Input: mat = [[1,2,3,4]]
Output: [1,2,3,4]
💡 Note: With only one row, each element forms its own diagonal. Since we alternate direction but can't move up or down, we simply traverse left to right: [1,2,3,4].

Visualization

Tap to expand
Diagonal Traversal Pattern123456789STARTTraversal SequenceStep 1: 1 (start position)Step 2: 2 (up-right movement)Step 3: 4 (boundary hit, change direction)Step 4: 7,5,3 (down-left diagonal)Step 5: 6,8 (up-right again)Step 6: 9 (final element)Result: [1,2,4,7,5,3,6,8,9]
Understanding the Visualization
1
Initialize
Start at top-left (0,0) with up-right direction
2
Move Diagonally
Continue in current direction until hitting a boundary
3
Handle Boundaries
Change direction and find next starting position based on boundary rules
4
Repeat Pattern
Continue alternating directions until all elements are visited
Key Takeaway
🎯 Key Insight: The diagonal traversal creates a zigzag pattern where direction changes occur at matrix boundaries, following predictable rules that can be simulated efficiently.

Time & Space Complexity

Time Complexity
⏱️
O(m×n)

We visit each cell once to group by diagonal, then once more to build result

n
2n
Linear Growth
Space Complexity
O(m×n)

Extra space needed to store all diagonals before processing

n
2n
Linearithmic Space

Constraints

  • m == mat.length
  • n == mat[i].length
  • 1 ≤ m, n ≤ 104
  • 1 ≤ m * n ≤ 104
  • -105 ≤ mat[i][j] ≤ 105
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
42.0K Views
Medium-High Frequency
~18 min Avg. Time
1.9K 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