<p>Given a 2D integer array <code>nums</code>, return <em>all elements of </em><code>nums</code><em> in diagonal order as shown in the below images</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/04/08/sample_1_1784.png" style="width: 158px; height: 143px;" />
<pre>
<strong>Input:</strong> nums = [[1,2,3],[4,5,6],[7,8,9]]
<strong>Output:</strong> [1,4,2,7,5,3,8,6,9]
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/04/08/sample_2_1784.png" style="width: 230px; height: 177px;" />
<pre>
<strong>Input:</strong> nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]
<strong>Output:</strong> [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= nums[i].length &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= sum(nums[i].length) &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= nums[i][j] &lt;= 10<sup>5</sup></code></li>
</ul>

from typing import List

class Solution:
    def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:
        # Step 1: Traverse the 2D array to find the maximum sum of indices (i + j)
        max_diagonal = 0
        for i, row in enumerate(nums):
            max_diagonal = max(max_diagonal, i + len(row) - 1)
        
        # Step 2: Collect elements in a dictionary
        diagonal_elements = {}
        for i, row in enumerate(nums):
            for j, num in enumerate(row):
                if i + j in diagonal_elements:
                    diagonal_elements[i + j].append(num)
                else:
                    diagonal_elements[i + j] = [num]
        
        # Step 3: Construct the result list by iterating through the dictionary
        result = []
        for diagonal in range(max_diagonal + 1):
            if diagonal in diagonal_elements:
                # Reverse the list to maintain the order from top-right to bottom-left
                result.extend(reversed(diagonal_elements[diagonal]))
        
        return result

# Example 1
solution = Solution()
nums = [[1,2,3],[4,5,6],[7,8,9]]
print(solution.findDiagonalOrder(nums))  # Output: [1,4,2,7,5,3,8,6,9]

# Example 2
solution = Solution()
nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]
print(solution.findDiagonalOrder(nums))  # Output: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]
40353