Problem 1424

Abstract / Summary

Given a list of lists with rows of varying lengths, return all elements in diagonal order.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
19 lines | 698 bytes | submitted November 22, 2023 | GitHub   41% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 58% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Heap (Priority Queue)
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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:

  1. Pops the last element of the reversed row, which corresponds to the next element on the diagonal, and yields it.
  2. Checks whether the row has become empty after the pop. If so, the row is deleted from nums, and last is 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.93 | σ = 1.63

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
25 links | 14 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

11 solutions   November 22, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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