Sponsored
Sponsored
This approach involves a direct simulation of the diagonal traversal. We use two variables, i
and j
, to represent the current position in the matrix, and a boolean direction
to indicate whether we are moving upwards or downwards diagonally. The process toggles the direction once the boundaries of the matrix are reached, ensuring that the entire matrix is traversed correctly in a zig-zag order.
Time Complexity: O(m * n) as each element is processed once.
Space Complexity: O(m * n) needed for the output array.
1import java.util.ArrayList;
2import java.util.List;
3
4class Solution {
5 public int[] findDiagonalOrder(int[][] mat) {
6 if (mat.length == 0) return new int[0];
7 int m = mat.length, n = mat[0].length;
8 int[] result = new int[m * n];
9 int idx = 0, i = 0, j = 0;
10 int direction = 1;
11 while (idx < m * n) {
12 result[idx++] = mat[i][j];
13 if (direction == 1) { // Moving up
14 if (j == n - 1) { i++; direction = -1; }
15 else if (i == 0) { j++; direction = -1; }
16 else { i--; j++; }
17 } else { // Moving down
18 if (i == m - 1) { j++; direction = 1; }
19 else if (j == 0) { i++; direction = 1; }
20 else { i++; j--; }
21 }
22 }
23 return result;
24 }
25}
Java implementation uses arrays and manages index tracking with an auxiliary direction variable. The matrix mat
is iterated from top-left to bottom-right, switching directions on boundary conditions.
This approach leverages a hash map (or dictionary) to collect elements that belong to the same diagonal. The sum of the row and column indices i + j
serves as the key, grouping all elements located on the same diagonal. After populating the hash map, we extract and append these elements to the result array, reversing them as needed to maintain the diagonal order.
Time Complexity: O(m * n), visits each element once.
Space Complexity: O(m * n), required for temporary storage for diagonals.
1
Using HashMap
, the Java implementation tracks elements by diagonal sums. After accumulating elements in diagonals
, elements are appended to the result list in zig-zag order.