1. Group by Anti-Diagonal Index (Brute Force)
Intuition
In an m x n matrix, all cells with the same sum r + c lie on the same anti-diagonal. Group cells by r + c into m + n - 1 buckets. Reverse even-numbered buckets (or odd, depending on starting direction) and flatten into a 1D result list.
When to apply: Use to understand the diagonal invariant r + c == constant.
Bucket by (r + c) Trace
2 of 2 questions left todayMatrix: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Matrix: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]. Sums range from 0 to 4 (m + n - 2).
import java.util.*; public class Main { public static class Solution { public int[] findDiagonalOrder(int[][] mat) { if (mat == null || mat.length == 0) return new int[0]; int m = mat.length, n = mat[0].length; List<List<Integer>> buckets = new ArrayList<>(); for (int i = 0; i < m + n - 1; i++) buckets.add(new ArrayList<>()); for (int r = 0; r < m; r++) { for (int c = 0; c < n; c++) { buckets.get(r + c).add(mat[r][c]); } } int[] res = new int[m * n]; int idx = 0; for (int i = 0; i < buckets.size(); i++) { List<Integer> b = buckets.get(i); if (i % 2 == 0) { for (int j = b.size() - 1; j >= 0; j--) res[idx++] = b.get(j); } else { for (int j = 0; j < b.size(); j++) res[idx++] = b.get(j); } } return res; } } public static void main(String[] args) { Solution sol = new Solution(); int[][] mat = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; System.out.println("Diagonal order: " + Arrays.toString(sol.findDiagonalOrder(mat))); }}Time & Space Complexity
- Time complexity:
O(m * n)— All m*n cells are visited and added to buckets. - Space complexity:
O(m * n)— Buckets store all m*n elements.
Why Brute Force Doesn't Scale:
For a 10,000-element matrix, dynamic lists cause thousands of heap reallocations.
Direct diagonal calculation writes directly into a pre-allocated array of size M*N in 0 extra heap memory.