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.
1#include <vector>
2using namespace std;
3
4vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
5 if (mat.empty()) return {};
6 int m = mat.size(), n = mat[0].size();
7 vector<int> result;
8 result.reserve(m * n);
9 int i = 0, j = 0, direction = 1;
10 while (result.size() < m * n) {
11 result.push_back(mat[i][j]);
12 if (direction == 1) { // Moving up
13 if (j == n - 1) { i++; direction = -1; }
14 else if (i == 0) { j++; direction = -1; }
15 else { i--; j++; }
16 } else { // Moving down
17 if (i == m - 1) { j++; direction = 1; }
18 else if (j == 0) { i++; direction = 1; }
19 else { i++; j--; }
20 }
21 }
22 return result;
23}
The C++ solution is similar to the C version, utilizing a vector for efficient resizing and operations. The direction changes are handled similarly while iterating through the matrix.
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
JavaScript utilizes a Map
for keeping track of diagonal entries. After the map is built using coordinates, final diagonal content is unpacked into the output list.