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.
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.