Set Matrix Zeroes (Constant Space)

Medium

Description

Given an m x n integer matrix, if an element is 0, set its entire row and column to 0's. You must do it in place using O(1) extra space.

Examples

Input:matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output:[[1,0,1],[0,0,0],[1,0,1]]
Explanation:

Found 0 at position (1,1). Using O(1) space: use first row and column as markers. Mark matrix[1][0]=0 and matrix[0][1]=0 to indicate row 1 and column 1 need zeroing. Then iterate and set marked rows/columns to zero. Final: [[1,0,1],[0,0,0],[1,0,1]].

Input:matrix = [[1,2,3,4],[5,0,7,8],[9,10,11,12]]
Output:[[1,0,3,4],[0,0,0,0],[9,0,11,12]]
Explanation:

The zero is at position (1,1). This causes the entire row 1 to become zeros, and column 1 to become zeros, while other elements remain unchanged.

Input:matrix = [[0]]
Output:[[0]]
Explanation:

Single element matrix containing zero. Since there's only one element and it's already zero, the output remains the same. This tests the edge case of minimum matrix size.

Constraints

  • m == matrix.length
  • n == matrix[0].length
  • 1 ≤ m, n ≤ 200

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!