Skip to content

Commit ebafeb6

Browse files
authored
Created set_matrix_zeroes.py
1 parent 788d95b commit ebafeb6

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
"""
2+
Set Matrix Zeroes Algorithm
3+
---------------------------
4+
If an element in an m x n matrix is 0, set its entire row and column to 0.
5+
6+
Explanation:
7+
We use the first row and first column as markers to track which rows and
8+
columns should be zeroed, avoiding extra space usage (O(1) space complexity).
9+
10+
References:
11+
https://leetcode.com/problems/set-matrix-zeroes/
12+
13+
Doctest:
14+
>>> matrix = [
15+
... [1, 1, 1],
16+
... [1, 0, 1],
17+
... [1, 1, 1]
18+
... ]
19+
>>> set_matrix_zeroes(matrix)
20+
>>> matrix
21+
[[1, 0, 1], [0, 0, 0], [1, 0, 1]]
22+
"""
23+
24+
def set_matrix_zeroes(matrix: list[list[int]]) -> None:
25+
"""
26+
Modify the matrix in-place such that if an element is 0,
27+
its entire row and column are set to 0.
28+
29+
:param matrix: 2D list of integers
30+
:return: None (modifies matrix in-place)
31+
32+
Time Complexity: O(m * n)
33+
Space Complexity: O(1)
34+
"""
35+
rows = len(matrix)
36+
cols = len(matrix[0])
37+
col0 = 1
38+
39+
# Step 1: Mark rows and columns that need to be zeroed
40+
for i in range(rows):
41+
if matrix[i][0] == 0:
42+
col0 = 0
43+
for j in range(1, cols):
44+
if matrix[i][j] == 0:
45+
matrix[i][0] = 0
46+
matrix[0][j] = 0
47+
48+
# Step 2: Update the inner matrix cells
49+
for i in range(1, rows):
50+
for j in range(1, cols):
51+
if matrix[i][0] == 0 or matrix[0][j] == 0:
52+
matrix[i][j] = 0
53+
54+
# Step 3: Handle the first row
55+
if matrix[0][0] == 0:
56+
for j in range(cols):
57+
matrix[0][j] = 0
58+
59+
# Step 4: Handle the first column
60+
if col0 == 0:
61+
for i in range(rows):
62+
matrix[i][0] = 0

0 commit comments

Comments
 (0)