Set Matrix Zeroes - Problem

Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.

You must do it in place.

Follow up: Can you solve it using O(1) extra space?

Input & Output

Example 1 — Basic Matrix with Zero
$ Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
💡 Note: The zero at position (1,1) causes row 1 and column 1 to become all zeros
Example 2 — Multiple Zeros
$ Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
💡 Note: Zeros at (0,0) and (0,3) cause row 0, columns 0 and 3 to become zero
Example 3 — Single Row Matrix
$ Input: matrix = [[1,0,3]]
Output: [[0,0,0]]
💡 Note: Single row with a zero becomes entirely zero

Constraints

  • m == matrix.length
  • n == matrix[0].length
  • 1 ≤ m, n ≤ 200
  • -231 ≤ matrix[i][j] ≤ 231 - 1

Visualization

Tap to expand
Set Matrix Zeroes INPUT Original Matrix (3x3) 1 1 1 1 0 1 1 1 1 Zero found at [1][1] Input: [[1,1,1],[1,0,1],[1,1,1]] m = 3, n = 3 In-place modification required ALGORITHM STEPS 1 Check First Row/Col Track if they have zeros 2 Mark Using Flags Use 1st row/col as markers 1 0 1 0 Flag row Flag 3 Set Zeros (Inner) Iterate from [1][1], set zeros 4 Handle First Row/Col Zero out if flagged Complexity: Time: O(m * n) Space: O(1) - In-place! FINAL RESULT Modified Matrix 1 0 1 0 0 0 1 0 1 Row 1 zeroed (had zero) Col 1 zeroed (had zero) Output: [[1,0,1],[0,0,0],[1,0,1]] OK - O(1) Space Key Insight: Use the first row and first column of the matrix itself as flags to mark which rows/columns need to be zeroed. This eliminates the need for extra O(m+n) space, achieving O(1) space! TutorialsPoint - Set Matrix Zeroes | O(1) Space Using First Row/Column as Flags
Asked in
Microsoft 45 Amazon 38 Google 35 Apple 25
262.0K Views
High Frequency
~25 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen