Created LeetCode73 Set Matrix Zeros (Medium) #369 #458
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Created
Fixed #369
Question Link:- https://leetcode.com/problems/set-matrix-zeroes/
Language-Java
Question-
Given an m x n integer matrix 'matrix', if an element is 0, set its entire row and column to 0's.
You must do it in place.
Intuition-
2.1 Brute Force
Traverse through the entire array, element by element, if the element is zero, traverse the column and row for it to make them '-1' ( or any other non-zero number - making them zero in the first place would lead to unexpected results). This would take a Time O(n3).
2.2 Brute Force 2
You could create two 1-D arrays for storing the occurrence of zeros in each row and each column. In the end, setting all those rows/cols to zero if the respective 1-D array indicated so. But this would take an extra space for both the 1-D arrays.
Approach:-
Identify and Mark Zeros: Traverse the matrix and mark the first cell of corresponding rows and columns as zero if any element is zero. Use two boolean variables, firstRow and firstCol, to keep track of whether the first row or first column contains any zeros.
Make Rows and Columns Zeros: Iterate through the matrix again, excluding the first row and the first column, and set the elements to zero if the corresponding row or column's first element is zero.
Update First Row and First Column: Finally, based on the boolean flags firstRow and firstCol, if any of them are true, update the entire first row or first column to zero accordingly.
Complexities:-
Time - O(n2),since the minimum time to traverse a 2-D array is O(n2)
Space- O(1), since no extra space
How to Proceed:-