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

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Code :

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription