Algorithm-Day18-Set-Matrix-Zeroes-lc-73
🧩 Problem Description
Given an m x n
integer matrix, if an element is 0
, set its entire row and column to 0
.
You must do it in place.
Example:
1 | Input: matrix = [[1,1,1],[1,0,1],[1,1,1]] |
💡 Brute Force (Not Ideal)
- Mark all rows and columns with zeros using extra sets.
- Time: O(m × n)
- Space: O(m + n) → uses extra memory, not fully in-place.
💡 Optimal Approach: Constant Space Using First Row and Column
✨ Key Idea
- Use the first row and first column as markers for rows and columns that need to be zeroed.
- Two passes:
- Mark rows/columns.
- Set cells to zero based on markers.
- Special care is needed for handling the first row and column separately.
🔢 Java Code
1 | class Solution { |
⏱ Time and Space Complexity
- Time Complexity: O(m × n)
Two passes over the matrix. - Space Complexity: O(1)
No extra space beyond the matrix itself.
✍️ Summary
- Smart use of the matrix itself as storage avoids extra space usage.
- Watch out for the first row and first column edge cases.
- Similar in-place patterns appear in other matrix transformation problems.
Learning how to reuse input space for flags is a useful technique in constrained-space algorithm design.