Approach
Sorting and greedy selection
For Sort Matrix by Diagonals, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 31 lines of Java from the credited upstream file 3446.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 5 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int[][] sortMatrix(int[][] grid) {3 final int n = grid.length;4 int[][] ans = new int[n][n];5 Map<Integer, List<Integer>> diag = new HashMap<>();6 7 for (int i = 0; i < n; ++i)8 for (int j = 0; j < n; ++j) {9 final int key = i - j;10 diag.putIfAbsent(key, new ArrayList<>());11 diag.get(key).add(grid[i][j]);12 }13 14 for (Map.Entry<Integer, List<Integer>> entry : diag.entrySet()) {15 List<Integer> values = entry.getValue();16 if (entry.getKey() < 0)17 Collections.sort(values, Collections.reverseOrder());18 else19 Collections.sort(values);20 }21 22 for (int i = 0; i < n; i++)23 for (int j = 0; j < n; j++) {24 final int key = i - j;25 ans[i][j] = diag.get(key).remove(diag.get(key).size() - 1);26 }27 28 return ans;29 }30}31