VOOZH about

URL: https://www.geeksforgeeks.org/dsa/remove-all-zero-rows-and-all-zero-columns-from-a-matrix/

⇱ Remove all zero-rows and all zero-columns from a Matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Remove all zero-rows and all zero-columns from a Matrix

Last Updated : 23 Jul, 2025

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: 

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:

  • Traverse the matrix and count 1s in rows and columns.
  • Now, traverse over the loop again and check for the following: 
    • If the count of 1s is found to be 0 for any row, skip that row.
    • If the count of 1s is found to be greater than 0 for any column, print that element.

Below is the implementation of the above approach:


Output
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:

  • Iterate over all rows one by one and check if that particular row contains all zeros or not.
    If, particular row contains all zeros then fill special integer to mark that row containing all zeros.
  • Iterate over all columns one by one and check if that particular column contains all zeros or not.
    If, particular column contains all zeros then fill special integer to mark that column containing all zeros.
  • Iterate over the matrix and check if any particular cell is marked with special integer.
    If yes, then skip that cell.
    Otherwise, print that cell.

Below is the implementation of above approach:


Output
111
111
011

Time complexity: O(N*M)
Auxiliary Space: O(1)

Comment