Python 0498.py
class Solution:
def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
width = len(mat[0])
height = len(mat)
dx = +1
dy = -1
x = 0
y = 0
result = []
while x != width - 1 or y != height - 1:
result.append(mat[y][x])
x += dx
y += dy
if x == width:
x -= 1
y += 2
dx, dy = dy, dx
if y == height:
x += 2
y -= 1
dx, dy = dy, dx
if x < 0 or y < 0:
x = max(x, 0)
y = max(y, 0)
dx, dy = dy, dx
result.append(mat[height - 1][width - 1])
return result
Difficulty
and has an acceptance rate of about 67% (800k+ submissions).
Typical patterns to solve this problem:
- Array
- Matrix
- Simulation
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation walks a two-dimensional array in the “zig-zag” diagonal order required by the problem statement. It maintains a current coordinate (x, y) and a direction vector (dx, dy). By repeatedly moving one step along the direction and correcting the position when a border is reached, the algorithm visits every cell exactly once and records its value in the output list.
Initialization
The code first determines the dimensions of the matrix.
width = len(mat[0])
height = len(mat)
The direction is set to move up-right initially (dx = +1, dy = -1). The starting cell is the top-left corner (x = 0, y = 0). An empty list result is prepared to collect the traversal order.
dx = +1
dy = -1
x = 0
y = 0
result = []
Main Traversal Loop
The core of the algorithm is a while loop that continues until the cursor reaches the bottom-right corner. The loop condition checks that either the column index is not at the last column or the row index is not at the last row.
while x != width - 1 or y != height - 1:
Inside the loop the current element is appended to the result.
result.append(mat[y][x])
The cursor then advances one step along the current direction.
x += dx
y += dy
Border Corrections
When the move steps outside the matrix, the code performs a corrective shift and flips the direction.
If the column index exceeds the right border
if x == width:
x -= 1
y += 2
dx, dy = dy, dx
The cursor is moved back one column, down two rows, and the direction components are swapped, effectively turning the movement from up-right to down-left.
If the row index exceeds the bottom border
if y == height:
x += 2
y -= 1
dx, dy = dy, dx
The cursor is moved right two columns, up one row, and the direction is swapped, turning the movement from down-left to up-right.
If the cursor goes negative on either axis
if x < 0 or y < 0:
x = max(x, 0)
y = max(y, 0)
dx, dy = dy, dx
The negative coordinate is clamped to zero, and the direction is swapped. This case handles the transition when the traversal reaches the top or left edge after moving diagonally.
Final Element
When the loop exits, the cursor is positioned at the bottom-right cell, which has not yet been added. The algorithm appends this last element explicitly.
result.append(mat[height - 1][width - 1])
The completed list is then returned.
return result
Edge Cases Handled
The logic for correcting out-of-bounds positions ensures correct behavior when the matrix has a single row. In that situation the initial direction attempts to move up-right, immediately triggers the x == width correction, and the algorithm proceeds horizontally across the row.
Similarly, a single column triggers the y == height correction after the first upward move, causing the cursor to step down the column correctly.
When the matrix is a 1 × 1 grid, the while condition is false from the start, and only the final explicit append executes, returning a list containing the sole element.
The negative-coordinate guard also covers the moment when a diagonal step would land above the top row or left of the first column, guaranteeing that the traversal never accesses an invalid index.
Performance Optimizations
The algorithm uses a single mutable list to accumulate results, avoiding the creation of intermediate collections. Direction changes are performed by swapping the two integer variables dx and dy, which is a constant-time operation and eliminates the need for conditional branches that would recompute the direction vector from scratch.
All index calculations are simple integer additions and subtractions; there are no nested loops or recursive calls, so the traversal proceeds in a straight linear pass over the matrix cells. The only auxiliary storage is the output list, whose size grows exactly to the number of matrix elements, matching the minimal requirement for the result.
By handling border conditions immediately after each step, the code prevents unnecessary checks inside the main loop body, keeping the per-iteration work minimal. This design yields an efficient execution path that scales directly with the number of elements in the input matrix.
ELI5 - Simplified Explanation
Imagine a grid filled with colorful numbered blocks, like a game board. The goal is to walk across every block by moving along diagonal lines, almost like drawing a Z shape over and over again.
First, the code looks at how wide and tall the grid is to see how much space there is to explore. It keeps track of a little explorer starting at the very top left corner. To move diagonally, the explorer needs to know which way is sideways and which way is up or down. Whenever a move is made, the explorer lands on a block and picks up the number written there to add to a collection.
Sometimes, the explorer might walk off the edge of the grid. If the explorer hits the right wall or the floor, the code helps them bounce back into the grid, like hitting a bumper in a pinball machine. When bouncing off a wall or a corner, the direction of the walk changes so the path continues cleanly. This jumping and bouncing continues until the explorer reaches the bottom right corner of the grid, ensuring every single number is collected along the wavy path.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | |||||||
| leetcode.ca | C++ | Java | Python | C# | Rust | Go | TS | ||
| LeetcodeHelp | C++ | Java | Python | ||||||
| MemoryLimitExceeded | C++ | Python | |||||||
| Progiez | C++ | Java | Python | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| Dijkstra-Edu | Java | ||||||||
| everthis | JS | ||||||||
| FelixFan1122 | Java | ||||||||
| fengvyi | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| linouk23 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| MacJim | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| YuriSpiridonov | Python | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Java | ||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| Dijkstra-Edu | Java | ||||||||
| everthis | JavaScript | ||||||||
| FelixFan1122 | Java | ||||||||
| fengvyi | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| linouk23 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| MacJim | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| YuriSpiridonov | Python | ||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 2075: Decode the Slanted Ciphertext
Solved On The Same Day
- problem 476: Number Complement
- problem 496: Next Greater Element I
- problem 6: Zigzag Conversion
- problem 38: Count and Say
- problem 147: Insertion Sort List
- problem 148: Sort List
- problem 494: Target Sum
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality