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 <= 1051 <= nums[i].length <= 1051 <= sum(nums[i].length) <= 1051 <= nums[i][j] <= 105This approach uses a hash map (or dictionary) to group elements that belong to the same diagonal. The sum of indices (i + j) of each element forms a unique key for each diagonal. We iterate over the 2D list, store elements based on their diagonal key, and then read each diagonal to form the result in the required traversal order.
This solution uses a dictionary to store elements by their diagonal key. We compute the diagonal key as the sum of row and column indices. For each diagonal, we store elements in a list. Finally, we sort the keys and concatenate the reversed lists (since lower diagonals need to come first in the result).
Java
C++
C
C#
JavaScript
Time Complexity: O(N), where N is the total number of elements, as we iterate over each element, and store them in the diagonals dictionary.
Space Complexity: O(N), due to the storage requirement for the diagonals dictionary.
Another approach is to flatten the 2D matrix into a list of triples containing the row index, column index, and value of each element. We then sort this list, prioritizing the sum of indices (i + j), followed by reversing elements when processed within the same diagonal, ensuring the correct order for traversing.
This solution begins by constructing a list of all (row, column, value) triples from the input. It sorts this list by (i + j) as a primary key (for diagonals), and by row in reverse order as a secondary key (to meet traversal requirements), easily extracting values for the result.
Java
C++
C
C#
JavaScript
Time Complexity: O(N log N) due to sorting operation.
Space Complexity: O(N), storing all elements in a list.
| Approach | Complexity |
|---|---|
| Hash Map to Group by Diagonals | Time Complexity: O(N), where N is the total number of elements, as we iterate over each element, and store them in the diagonals dictionary. |
| Flatten and Sort by Diagonal | Time Complexity: O(N log N) due to sorting operation. |
Diagonal Traverse | Live Coding with Explanation | Leetcode - 498 • Algorithms Made Easy • 48,928 views views
Watch 9 more video solutions →Practice Diagonal Traverse II with our built-in code editor and test cases.
Practice on FleetCode