Skip to content

Commit 265aa30

Browse files
committed
Sync LeetCode submission Runtime - 14 ms (44.74%), Memory - 19.7 MB (47.58%)
1 parent 062f3ea commit 265aa30

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

0498-diagonal-traverse/README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<p>Given an <code>m x n</code> matrix <code>mat</code>, return <em>an array of all the elements of the array in a diagonal order</em>.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
<img alt="" src="https://assets.leetcode.com/uploads/2021/04/10/diag1-grid.jpg" style="width: 334px; height: 334px;" />
6+
<pre>
7+
<strong>Input:</strong> mat = [[1,2,3],[4,5,6],[7,8,9]]
8+
<strong>Output:</strong> [1,2,4,7,5,3,6,8,9]
9+
</pre>
10+
11+
<p><strong class="example">Example 2:</strong></p>
12+
13+
<pre>
14+
<strong>Input:</strong> mat = [[1,2],[3,4]]
15+
<strong>Output:</strong> [1,2,3,4]
16+
</pre>
17+
18+
<p>&nbsp;</p>
19+
<p><strong>Constraints:</strong></p>
20+
21+
<ul>
22+
<li><code>m == mat.length</code></li>
23+
<li><code>n == mat[i].length</code></li>
24+
<li><code>1 &lt;= m, n &lt;= 10<sup>4</sup></code></li>
25+
<li><code>1 &lt;= m * n &lt;= 10<sup>4</sup></code></li>
26+
<li><code>-10<sup>5</sup> &lt;= mat[i][j] &lt;= 10<sup>5</sup></code></li>
27+
</ul>

0498-diagonal-traverse/solution.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Approach 1: Diagonal Iteration and Reversal
2+
3+
# Time: O(n * m)
4+
# Space: O(min(n, m))
5+
6+
class Solution:
7+
def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
8+
if not mat or not mat[0]:
9+
return []
10+
11+
n, m = len(mat), len(mat[0])
12+
13+
result, intermediate = [], []
14+
15+
for d in range(n + m - 1):
16+
intermediate.clear()
17+
18+
# We need to figure out the "head" of this diagonal
19+
# The elements in the first row and the last column
20+
# are the respective heads.
21+
r, c = 0 if d < m else d - m + 1, d if d < m else m - 1
22+
23+
# Iterate until one of the indices goes out of scope
24+
# Take note of the index math to go down the diagonal
25+
while r < n and c > -1:
26+
intermediate.append(mat[r][c])
27+
r += 1
28+
c -= 1
29+
30+
# Reverse even numbered diagonals. The
31+
# article says we have to reverse odd
32+
# numbered articles but here, the numbering
33+
# is starting from 0 :P
34+
if d % 2 == 0:
35+
result.extend(intermediate[::-1])
36+
else:
37+
result.extend(intermediate)
38+
39+
return result
40+

0 commit comments

Comments
 (0)