Striver-SDE-Sheet

Repository containing solution for #SdeSheetChallenge by striver

View the Project on GitHub

Set Matrix Zeroes

Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0’s, and return the matrix.You must do it in place.

Brute Force

Optimization using extra space

Code

// codestudio
#include <bits/stdc++.h>
void setZeros(vector<vector<int>> &matrix)
{
    set<int> rows, cols;
    int n = matrix.size();
    int m = matrix[0].size();
    for(int i = 0 ; i< n ; i++){
        for(int j = 0 ; j < m ; j++){
            if(matrix[i][j]==0){
                rows.insert(i);
                cols.insert(j);
            }
        }
    }
    for(auto x:rows){
        for(int j = 0; j < m; j++){
            matrix[x][j] = 0;
        }
    }
    for(auto x:cols){
        for(int i = 0; i < n; i++){
            matrix[i][x] = 0;
        }
    }
}

O(1) Space Optimization

Code

// leetcode
class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix)
    {
        int r = matrix.size(), c = matrix[0].size();
        bool col = true;

        for (int i = 0; i < r; i++) { // Traverse all rows
            if (matrix[i][0] == 0) col = false; // if Element of first column is 0, set col = false
            for (int j = 1; j < c; j++) // Traverse all cols except first
                if (matrix[i][j] == 0) {
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
        }

        // traverse from backwards
        for (int i = r - 1; i >= 0; i--) {
            for (int j = c - 1; j >= 1; j--)
                if (matrix[i][0] == 0 || matrix[0][j] == 0) // if any marker array has 0 set i,j th Element to 0
                    matrix[i][j] = 0;
            // if col = false, means whole col is 0.
            if (col == false) matrix[i][0] = 0;
        }
    }
};