Skip to content

Commit

Permalink
Sync LeetCode submission Runtime - 14 ms (44.74%), Memory - 19.7 MB (…
Browse files Browse the repository at this point in the history
…47.58%)
  • Loading branch information
jimit105 committed Dec 29, 2024
1 parent 062f3ea commit 265aa30
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
27 changes: 27 additions & 0 deletions 0498-diagonal-traverse/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<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>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/04/10/diag1-grid.jpg" style="width: 334px; height: 334px;" />
<pre>
<strong>Input:</strong> mat = [[1,2,3],[4,5,6],[7,8,9]]
<strong>Output:</strong> [1,2,4,7,5,3,6,8,9]
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> mat = [[1,2],[3,4]]
<strong>Output:</strong> [1,2,3,4]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
<li><code>m == mat.length</code></li>
<li><code>n == mat[i].length</code></li>
<li><code>1 &lt;= m, n &lt;= 10<sup>4</sup></code></li>
<li><code>1 &lt;= m * n &lt;= 10<sup>4</sup></code></li>
<li><code>-10<sup>5</sup> &lt;= mat[i][j] &lt;= 10<sup>5</sup></code></li>
</ul>
40 changes: 40 additions & 0 deletions 0498-diagonal-traverse/solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Approach 1: Diagonal Iteration and Reversal

# Time: O(n * m)
# Space: O(min(n, m))

class Solution:
def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
if not mat or not mat[0]:
return []

n, m = len(mat), len(mat[0])

result, intermediate = [], []

for d in range(n + m - 1):
intermediate.clear()

# We need to figure out the "head" of this diagonal
# The elements in the first row and the last column
# are the respective heads.
r, c = 0 if d < m else d - m + 1, d if d < m else m - 1

# Iterate until one of the indices goes out of scope
# Take note of the index math to go down the diagonal
while r < n and c > -1:
intermediate.append(mat[r][c])
r += 1
c -= 1

# Reverse even numbered diagonals. The
# article says we have to reverse odd
# numbered articles but here, the numbering
# is starting from 0 :P
if d % 2 == 0:
result.extend(intermediate[::-1])
else:
result.extend(intermediate)

return result

0 comments on commit 265aa30

Please sign in to comment.