Python 1424.py
class Solution:
def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:
# removing first element of a list might be slow, let's reverse all of them
for y in range(len(nums)):
nums[y] = list(reversed(nums[y]))
last = 0 # max row in current pass
while nums:
# process an "arrow" / a slice
for y in range(last, -1, -1):
yield nums[y].pop()
# remove row if empty
if not nums[y]:
del nums[y]
last -= 1
# one more row in next pass, but don't leave grid
last = min(last + 1, len(nums) - 1)
Difficulty
and has an acceptance rate of about 58% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Heap (Priority Queue)
- Sorting
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 provided Solution.findDiagonalOrder method produces a diagonal traversal of a ragged two-dimensional list nums. It yields elements in the order required by the “diagonal order” problem, where each diagonal is read from top-right to bottom-left. The implementation works directly on the input structure, mutating it to avoid extra indexing work, and uses a generator (yield) to emit the result lazily.
Reversing rows to enable efficient popping
for y in range(len(nums)):
nums[y] = list(reversed(nums[y]))
Each inner list is reversed in place. By doing this, the algorithm can later call pop() on the end of the list, which is an O(1) operation. This avoids the O(n) cost associated with removing the first element (pop(0)) in a Python list. The reversal step is a one-time cost proportional to the total number of elements.
Controlling the active row range
last = 0 # max row index considered in the current pass
The variable last tracks the highest row index that participates in the current diagonal slice. It starts at the first row and expands gradually as new rows become reachable in subsequent diagonals.
Main processing loop
while nums:
for y in range(last, -1, -1):
yield nums[y].pop()
if not nums[y]:
del nums[y]
last -= 1
last = min(last + 1, len(nums) - 1)
The outer while loop continues until all rows have been exhausted and removed from nums. Inside, a reverse for loop iterates from last down to 0, representing the current diagonal slice. For each row y in that slice, the algorithm:
- Pops the last element of the reversed row, which corresponds to the next element on the diagonal, and yields it.
- Checks whether the row has become empty after the pop. If so, the row is deleted from
nums, andlastis decremented to reflect the reduced number of active rows.
After completing a diagonal slice, last is incremented by one (capped at the current number of rows minus one) so that the next pass includes one additional row, matching the expanding shape of the diagonals.
Edge-case handling
When nums is empty from the start, the outer while condition fails immediately, and the generator produces no output. Rows of differing lengths are naturally accommodated because each row is processed only while it still contains elements; shorter rows simply disappear earlier, and the del nums[y] step removes them from further consideration. The adjustment of last after a row deletion ensures that the loop does not attempt to access an index that no longer exists. The min call when updating last prevents it from exceeding the highest valid index after rows have been removed, guaranteeing safe iteration even when the number of rows shrinks dramatically between passes.
Performance-focused design choices
The reversal of each inner list eliminates the need for costly front-side deletions, turning every element removal into a constant-time pop. Deleting empty rows from nums reduces the size of the container as the algorithm progresses, which shortens the range of the inner loop and avoids unnecessary checks on rows that have already been exhausted. The incremental growth of last mirrors the natural expansion of diagonals, so each pass processes exactly the rows that contribute new elements, avoiding redundant scans of rows that are not part of the current diagonal. By yielding elements directly, the method avoids constructing an intermediate list, allowing the caller to consume results on the fly and reducing peak memory usage.
ELI5 - Simplified Explanation
Imagine a giant grid filled with numbers, almost like a tray of delicious cookies arranged in little cubbies. The goal is to grab all the cookies one by one, but following a zig-zag path that travels diagonally across the tray.
First, the code takes every single row of cookies and flips them around backwards. This makes it much easier to reach into the end of each row and pluck out the cookies as needed.
Then, the program starts a loop that keeps going until every last cookie is gone from the tray. Inside this loop, it looks at the current rows and moves along an invisible diagonal arrow. It reaches into a row, scoops up the very last cookie, and pulls it out. Whenever a row becomes completely empty because all its cookies were taken, that empty row is thrown away so the computer does not have to worry about it anymore.
After finishing that diagonal path, the program moves its focus to include one extra row for the next trip across the tray. It stays careful to keep its reach inside the boundaries of the tray, making sure it never tries to grab cookies from a place where there are none. This repeats over and over, jumping around the grid in diagonal lines until the whole tray is clean.
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++ | Python | Java | TS | ||||
| WalkCCC | C++ | Java | |||||||
| leetcode.ca | C++ | Python | Java | C# | Go | TS | |||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| martianoff | Scala | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Java | ||||||||
| leetcode.ca | C++, C#, Go, Java, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| martianoff | Scala | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 2558: Take Gifts From the Richest Pile
- problem 395: Longest Substring with At Least K Repeating Characters
- problem 932: Beautiful Array
- problem 1382: Balance a Binary Search Tree
- problem 2406: Divide Intervals Into Minimum Number of Groups
- problem 2593: Find Score of an Array After Marking All Elements
- problem 2611: Mice and Cheese
- problem 2679: Sum in a Matrix
- problem 493: Reverse Pairs
- problem 2551: Put Marbles in Bags
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