![]() |
VOOZH | about |
Given a matrix arr[][] of size N * M, the task is to print the matrix after removing all rows and columns from the matrix which consists of 0s only.
Examples:
Input: arr[][] ={ { 1, 1, 0, 1 }, { 0, 0, 0, 0 }, { 1, 1, 0, 1}, { 0, 1, 0, 1 } }
Output:
111
111
011
Explanation:
Initially, the matrix is as follows:
arr[][] = { { 1, 1, 0, 1 },
{ 0, 0, 0, 0 },
{ 1, 1, 0, 1 },
{ 0, 1, 0, 1 } }
Removing the 2nd row modifies the matrix to:
arr[][] = { { 1, 1, 0, 1 },
{ 1, 1, 0, 1 },
{ 0, 1, 0, 1 } }
Removing the 3rd column modifies the matrix to:
arr[][] = { { 1, 1, 1 },
{ 1, 1, 1 },
{ 0, 1, 1 } }Input: arr={{0, 1}, {0, 1}}
Output:
1
1
Approach: The idea is to count the number of 0s in all the rows and columns of the matrix and check if any rows or columns consist only of 0s or not. If found to be true, then remove those rows or the columns of the matrix. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
111 111 011
Time complexity: O(N*M)
Auxiliary Space: O(N+M)
Another efficient approach: The idea is to mark all rows and columns that contain all zeros with some other special integer (a value that is not present in the matrix) to identify that we do not need that particular row or column and whenever we reach While iterating over the matrix on that particular integer we skip that cell because we assume that the cell has been removed while deletion of the row or column which has all zeros.
Follow the below steps to implement the idea:
Below is the implementation of above approach:
111 111 011
Time complexity: O(N*M)
Auxiliary Space: O(1)