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.
1from typing import List
2
3def findDiagonalOrder(mat: List[List[int]]) -> List[int]:
4 if not mat: return []
5 m, n = len(mat), len(mat[0])
6 result, i, j, direction = [], 0, 0, 1
7 while len(result) < m * n:
8 result.append(mat[i][j])
9 if direction == 1: # Moving up
10 if j == n - 1: i, direction = i + 1, -1
11 elif i == 0: j, direction = j + 1, -1
12 else: i, j = i - 1, j + 1
13 else: # Moving down
14 if i == m - 1: j, direction = j + 1, 1
15 elif j == 0: i, direction = i + 1, 1
16 else: i, j = i + 1, j - 1
17 return result
This Python solution tracks indices i
and j
while adjusting direction at matrix boundaries. result
list collects elements in diagonal order, switching direction using a direction
flag.
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.
1using System.Collections.Generic;
public class Solution {
public int[] FindDiagonalOrder(int[][] mat) {
int m = mat.Length, n = mat[0].Length;
Dictionary<int, List<int>> diagonals = new Dictionary<int, List<int>>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (!diagonals.ContainsKey(i + j)) diagonals[i + j] = new List<int>();
diagonals[i + j].Add(mat[i][j]);
}
}
List<int> result = new List<int>();
for (int k = 0; k < m + n - 1; k++) {
if (k % 2 == 0) diagonals[k].Reverse();
result.AddRange(diagonals[k]);
}
return result.ToArray();
}
}
In C#, the Dictionary
tools are employed to group elements across the same diagonal, denoted by index sums. Collections are concatenated in order with reversal where needed.