Set Matrix Zeroes LeetCode Solution

Set Matrix Zeroes Leetcode Solution :

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

Set Matrix Zeroes

Set Matrix Zeroes LeetCode Solution :

Constraints :

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

Example 1:

  • 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]]

Approach:

  1. First, the code initializes two dummy vectors, dummyRow and dummyCol, with initial values of -1. These vectors will be used to mark the rows and columns that need to be set to zero.
  2. The code then iterates through each element of the matrix and checks if it is zero. If an element is zero, it updates the corresponding indices in dummyRow and dummyCol to 0.
  3. After marking the rows and columns, the code iterates through the matrix again. For each element, it checks if the corresponding row index or column index in dummyRow or dummyCol is zero. If either of them is zero, it sets the current element to zero.
  4. Finally, the matrix will have rows and columns set to zero based on the values in dummyRow and dummyCol.

Complexity:

  • Time Complexity: O(mn), where m and n are the number of rows and columns in the matrix, respectively. We have to traverse the matrix twice.
  • Space Complexity: O(m+n), where m and n are the number of rows and columns in the matrix, respectively. We are using two auxiliary vectors of size m and n to keep track of the rows and columns that contain zero elements.
Set Matrix Zeroes

Code :