Diagonal Traverse II (LeetCode 1424): Solution and Explanation

Medium
Array
Sorting
Heap Priority Queue

Given a jagged 2D array where rows can have different lengths, list every element diagonal by diagonal: diagonals in increasing i + j, and each diagonal from bottom-left to top-right.

Intuition

Every cell (i, j) sits on diagonal d = i + j, so the answer is just the cells grouped by d, groups in increasing order.

The tricky part is the order inside a group: bottom-left first means the larger row index comes first. If we scan rows from the bottom up and append each value to its bucket, the buckets fill in exactly that order.

Walking the full bounding rectangle would be a trap. One row of length 100,000 next to 100,000 rows of length 1 makes the rectangle 10^10 cells, while only 2 * 10^5 cells exist. Bucketing touches each real cell once.

Once every cell is in its bucket, reading the buckets from d = 0 upward gives the answer directly, with no sorting.

Approach: Bucket by i + j, rows bottom-up

  1. Create an empty list of buckets groups.
  2. For i from the last row down to 0, and for each j in row i: grow groups until index i + j exists, then append nums[i][j] to groups[i + j].
  3. Concatenate the buckets in order groups[0], groups[1], ... and return the result.

Step-by-step example

nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]
  1. Row 4 (12..16) goes to buckets 4..8: each bucket starts with its bottom value.
  2. Row 3 (9,10,11) appends to buckets 3, 4, 5, so bucket 4 is now [12,10].
  3. Row 2 (8) appends to bucket 2; row 1 (6,7) appends to buckets 1 and 2, so bucket 2 is [8,7].
  4. Row 0 (1..5) appends to buckets 0..4, giving bucket 3 = [9,4] and bucket 4 = [12,10,5].
  5. Joining buckets 0..8 gives [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16].

Code: Python, Java, C++

1class Solution:
2    def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:
3        groups = []
4        for i in range(len(nums) - 1, -1, -1):
5            for j, v in enumerate(nums[i]):
6                while len(groups) <= i + j:
7                    groups.append([])
8                groups[i + j].append(v)
9        return [v for g in groups for v in g]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Bucket by i + j, rows bottom-up O(N)
BFS from the top-left corner O(N)
Sort by (i + j, -i) O(N log N)
Time

O(N)

Each of the N elements is appended once and copied to the output once. The number of buckets is at most N as well, since the largest i + j is below the total element count.

Space

O(N)

The buckets hold every element once, besides the output array.

Other approaches

BFS from the top-left corner (time O(N), space O(length of the longest diagonal))

Start a queue at (0,0). When popping (i, j), push (i+1, j) only if j == 0, then push (i, j+1) if it exists. The queue then yields cells diagonal by diagonal in bottom-left to top-right order, and the queue only ever holds about one diagonal.

Sort by (i + j, -i) (time O(N log N), space O(N))

Collect (i + j, -i, value) for every cell and sort. Simple and correct, but the sort adds a log factor.

Common mistakes

  • Iterating over a full rows x maxCols rectangle and skipping missing cells, which times out on jagged inputs.
  • Scanning rows top-down, which puts each diagonal in top-right to bottom-left order.
  • Assuming bucket i + j already exists: with jagged rows, the first cell seen can jump past several missing buckets, so grow the list with a loop rather than a single append.
  • Reusing the zigzag direction logic from Diagonal Traverse (LC 498); here every diagonal goes the same way.

Frequently asked questions

How is this different from Diagonal Traverse (LC 498)?

LC 498 has a rectangular matrix and alternates direction on each diagonal. Here rows are jagged and every diagonal goes bottom-left to top-right, so bucketing by i + j works without any direction flips.

Why scan rows from the bottom?

Inside a diagonal the larger row index must come first. Appending in bottom-up row order puts the larger row index earlier in each bucket, so no reversal or sorting is needed.

Can a bucket be empty?

No. Row 0 has at least one cell and every row is non-empty, so diagonal d always contains a cell from some row. The grow-loop is still needed because buckets are first touched out of order while scanning bottom-up.