Matrix Zeroing

Languages

Given a matrix of size m x n, modify the matrix such that if an element is 0, its entire row and column are set to 0. The changes should be made in-place, i.e. directly to the original matrix.

Input

  • matrix: number[][]: A 2D array matrix of size m x n

Examples

Input: matrix = [[1,2,0],[4,0,6],[7,8,9]]
Output: [[0,0,0],[0,0,0],[7,0,0]]
Explanation: The elements at (row 0, column 2) and (row 1, column 1) are 0, so their corresponding rows and columns are set to 0.
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,2,3],[4,5,6],[7,8,9]]
Explanation: There are no zeroes in the matrix, so no changes are made.
Input: matrix = [[1,2],[3,4],[5,0],[7,8]]
Output: [[1,0],[3,0],[0,0],[7,0]]
Explanation: The element at (row 2, column 1) is 0, so its corresponding rows and columns are set to 0.

Constraints

  • 1 <= m, n <= 100
  • -1,000 <= matrix[row][col] <= 1,000
  • Challenge: Use only O(1) extra space

Hints

New

Asked at these companies

Unlock company signalsPremium shows which companies ask this question so you can prioritize practice by target company.
Unlock

Loading editor

    Matrix Zeroing | Algorithms Interview Questions with Solutions