This 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.
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.
1def findDiagonalOrder(nums):
2 diagonals = {}
3 for i in range(len(nums)):
4 for j in range(len(nums[i])):
5 if (i + j) not in diagonals:
6 diagonals[i + j] = []
7 diagonals[i + j].append(nums[i][j])
8 result = []
9 for k in sorted(diagonals.keys()):
10 result.extend(reversed(diagonals[k]))
11 return result
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).
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.
Time Complexity: O(N log N) due to sorting operation.
Space Complexity: O(N), storing all elements in a list.
1def findDiagonalOrder(nums):
2 elements = []
3 for r, row in enumerate(nums):
4 for c, val in enumerate(row):
5 elements.append((r, c, val))
6 elements.sort(key=lambda x: (x[0] + x[1], -x[0]))
7 return [val for _, _, val in elements]
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.