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.
1var findDiagonalOrder = function(mat) {
2 if (mat.length === 0) return [];
3 let m = mat.length, n = mat[0].length;
4 let result = [], i = 0, j = 0, direction = 1;
5 while (result.length < m * n) {
6 result.push(mat[i][j]);
7 if (direction === 1) { // Moving up
8 if (j === n - 1) { i++; direction = -1; }
9 else if (i === 0) { j++; direction = -1; }
10 else { i--; j++; }
11 } else { // Moving down
12 if (i === m - 1) { j++; direction = 1; }
13 else if (j === 0) { i++; direction = 1; }
14 else { i++; j--; }
15 }
16 }
17 return result;
18};
In JavaScript, this solution iterates in a similar diagonal manner, utilizing a toggle direction
variable. The result
array collects elements along the path as defined by i
and j
.
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
Python uses defaultdict
to manage lists of diagonal elements. The i + j
sum serves as the key, organizing elements for later collection into a single output result
list based on zig-zag criteria.