498. Diagonal Traverse
Problem description:
Given an m x n
matrix mat
, return an array of all the elements of the array in a diagonal order.
Example 1:
1 | Input: mat = [[1,2,3],[4,5,6],[7,8,9]] |
Example 2:
1 | Input: mat = [[1,2],[3,4]] |
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
105 <= mat[i][j] <= 105
Solution:
The key here is to realize that the sum of indices on all diagonals are equal
.For example, in
1 | [1,2,3] |
2, 4 are on the same diagonal, and they share the index sum of 1. (2 is matrix[0][1] and 4 is in matrix[1][0]). 3,5,7 are on the same diagonal, and they share the sum of 2. (3 is matrix[0][2], 5 is matrix[1][1], and 7 is matrix [2][0]).
1 | class Solution: |
time complexity: $O(mn)$
space complexity: $O(mn)$
reference:
related problem: