#498
Diagonal Traverse
MediumArrayMatrixSimulationArrayMatrix
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution leverages the understanding of how diagonals are formed in the matrix and uses a single loop to traverse through the diagonals efficiently, reducing unnecessary checks.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an empty list to store the result.
- 2Step 2: Use a single loop to iterate through the sum of indices (d) from 0 to m + n - 2.
- 3Step 3: Depending on whether d is even or odd, determine the starting point and direction of traversal, collecting elements along the diagonal.
solution.py23 lines
1# Full working Python code
2
3def findDiagonalOrder(mat):
4 if not mat:
5 return []
6 m, n = len(mat), len(mat[0])
7 result = []
8 for d in range(m + n - 1):
9 if d % 2 == 0:
10 row = min(d, m - 1)
11 col = d - row
12 while row >= 0 and col < n:
13 result.append(mat[row][col])
14 row -= 1
15 col += 1
16 else:
17 col = min(d, n - 1)
18 row = d - col
19 while col >= 0 and row < m:
20 result.append(mat[row][col])
21 row += 1
22 col -= 1
23 return resultℹ
Complexity note: The time complexity is O(n) because we traverse each element of the matrix once. The space complexity is O(n) for storing the result array.
- 1Understanding the pattern of diagonal traversal helps in optimizing the solution.
- 2Recognizing the direction of traversal (up or down) based on the sum of indices is crucial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.