Solve LeetCode 73: Set Matrix Zeroes in Python with a first-row marker compression approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.
This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Matrix |
| Reusable pattern | first-row marker compression |
| Complexity | O(mn) time and O(1) extra space |
What the problem is testing
Use the first row and column as marker storage, preserving separate flags for whether those marker lines originally contained zero.
Algorithm
- Use the first row and column as marker storage, preserving separate flags for whether those marker lines originally contained zero.
- Maintain this invariant: A marker at row r or column c records that every cell on that line must become zero.
- Continue until every input item or reachable state has been resolved, then return the accumulated result.
Python solution
from collections import Counter, defaultdict, deque, OrderedDict
import random
class Solution:
def setZeroes(self, matrix):
rows, cols = len(matrix), len(matrix[0])
first_row = any(matrix[0][c] == 0 for c in range(cols))
first_col = any(matrix[r][0] == 0 for r in range(rows))
for r in range(1, rows):
for c in range(1, cols):
if matrix[r][c] == 0: matrix[r][0] = matrix[0][c] = 0
for r in range(1, rows):
for c in range(1, cols):
if matrix[r][0] == 0 or matrix[0][c] == 0: matrix[r][c] = 0
if first_row:
for c in range(cols): matrix[0][c] = 0
if first_col:
for r in range(rows): matrix[r][0] = 0Why this is correct
The proof follows the maintained state: A marker at row r or column c records that every cell on that line must become zero. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.
Complexity
O(mn) time and O(1) extra space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.
Edge cases
The top-left cell is shared by both marker lines, so row and column flags must be separate.
Tested reference code
This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 48. Rotate Image · Next: 289. Game of Life