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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int[] FindDiagonalOrder(IList<IList<int>> nums) {
6 var diagonals = new Dictionary<int, List<int>>();
7 int maxKey = 0;
8 foreach (var i in nums)
9 {
10 foreach (var j in i)
11 {
12 int key = j + nums.IndexOf(i);
13 if (!diagonals.ContainsKey(key))
14 {
15 diagonals[key] = new List<int>();
16 }
17 diagonals[key].Add(i[j]);
18 if (key > maxKey) maxKey = key;
19 }
20 }
21 var result = new List<int>();
22 for (int key = 0; key <= maxKey; key++)
23 {
24 if (diagonals.ContainsKey(key))
25 {
26 diagonals[key].Reverse();
27 result.AddRange(diagonals[key]);
28 }
29 }
30 return result.ToArray();
31 }
32}
The C# implementation uses a dictionary to categorize integers into their appropriate diagonal based on position sums. The solution processes each list of diagonals in reverse as desired in the problem’s specification, outputting the result as an array.
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.
1import java.util.*;
2
3class Solution {
4 public int[] findDiagonalOrder(List<List<Integer>> nums) {
5 List<int[]> elements = new ArrayList<>();
6 for (int i = 0; i < nums.size(); i++) {
7 for (int j = 0; j < nums.get(i).size(); j++) {
8 elements.add(new int[]{i, j, nums.get(i).get(j)});
9 }
10 }
11 Collections.sort(elements, (a, b) -> {
12 int cmp = (a[0] + a[1]) - (b[0] + b[1]);
13 return cmp != 0 ? cmp : b[0] - a[0];
14 });
15 int[] result = new int[elements.size()];
16 for (int k = 0; k < elements.size(); k++) {
17 result[k] = elements.get(k)[2];
18 }
19 return result;
20 }
21}
The Java solution collects elements with their indices into a list, which it sorts first by diagonal (i.e., the sum of indices), and secondly by row index, reversed. This permits easy creation of the result as values are extracted in final order.