Diagonal Traverse II Problem
Description
LeetCode Problem 1424.
Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images.
Example 1:

Input: nums = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,4,2,7,5,3,8,6,9]
Example 2:

Input: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]
Output: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]
Constraints:
1 <= nums.length <= 10^51 <= nums[i].length <= 10^51 <= sum(nums[i].length) <= 10^51 <= nums[i][j] <= 10^5
Solution
Approach: Group by Diagonal
Every cell (i, j) on the same diagonal has the same i + j, and the diagonals are printed in increasing order of i + j. So the whole job is to put each value into the right diagonal, in the right order inside it.
Inside one diagonal the order goes from bottom-left to top-right, which means rows from bottom to top. If we read the rows from the last one up to the first and append each value to the list for i + j, every list comes out already in the order we need. Then we just print the lists one after another.
Rows can have very different lengths (one row of 105 values, or 105 rows of one value), so walking the diagonals over a full rows x maxCols grid would touch far too many empty cells. Grouping only visits the cells that exist. The number of diagonals is at most rows + maxCols - 1, which is at most about 2 · 105.
Complexity: O(N) time and O(N) extra space, where N is the total number of values.
class Solution:
def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:
# buckets[d] holds the diagonal i + j = d, from bottom-left to top-right
buckets = []
for i in range(len(nums) - 1, -1, -1): # lower rows come first on a diagonal
for j, v in enumerate(nums[i]):
while len(buckets) <= i + j:
buckets.append([])
buckets[i + j].append(v)
return [v for diagonal in buckets for v in diagonal]