Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Matrix
  • Practice Matrix
  • MCQs on Matrix
  • Tutorial on Matrix
  • Matrix Traversal
  • Sorting in Matrix
  • Matrix Rotation
  • Transpose of Matrix
  • Inverse of Matrix
  • Determinant of Matrix
  • Matrix Application
  • Adjoint & Inverse Matrix
  • Sparse Matrix
  • Matrix Exponentiation
Open In App
Next Article:
Find and remove maximum value in each row of a given Matrix
Next article icon

Find row with maximum and minimum number of zeroes in given Matrix

Last Updated : 22 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a 2D matrix containing only zeroes and ones, where each row is sorted. The task is to find the row with the maximum number of 0s and the row with minimum number of 0s.
Example: 
 

Input: mat[][] = { 
{0, 1, 1, 1}, 
{0, 0, 1, 1}, 
{1, 1, 1, 1}, 
{0, 0, 0, 0}} 
Output: 
Row with min zeroes: 3 
Row with max zeroes: 4
Input: mat[][] = { 
{0, 1, 1, 1}, 
{0, 0, 1, 1}, 
{0, 0, 0, 1}, 
{0, 0, 0, 0}} 
Output: 
Row with min zeroes: 1 
Row with max zeroes: 4 
 

 

Simple approach: A simple method is to do a row-wise traversal of the matrix, count the number of 0s in each row, and compare the count with max and min. Finally, return the index of row with maximum 0s and minimum 0s. The time complexity of this method is O(M*N) where M is a number of rows and N is a number of columns in matrix.
Efficient approach: Since each row is sorted, we can use Binary Search to find the count of 0s in each row. The idea is to find the index of first instance of 1 in each row. 
The count of 0s in that row will be: 
 

  • If 1 exists in the row, then count of 0s will be equal to the index of first 1 in the row considering zero-based indexing.
  • If 1 does not exist in the row, then count of 0s will be N which is the total number of columns in the matrix.

Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define R 4
#define C 4
 
// Function to find the index of first 1
// in the binary array arr[]
int first(bool arr[], int low, int high)
{
    if (high >= low) {
 
        // Get the middle index
        int mid = low + (high - low) / 2;
 
        // Check if the element at middle index is first 1
        if ((mid == 0 || arr[mid - 1] == 0) && arr[mid] == 1)
            return mid;
 
        // If the element is 0, recur for right side
        else if (arr[mid] == 0)
            return first(arr, (mid + 1), high);
 
        // If element is not first 1, recur for left side
        else
            return first(arr, low, (mid - 1));
    }
    return -1;
}
 
// Function to print rows with maximum
// and minimum number of zeroes
void rowWith0s(bool mat[R][C])
{
    // Initialize max values
    int max_row_index = 0, max = INT_MIN;
 
    // Initialize min values
    int min_row_index = 0, min = INT_MAX;
 
    // Traverse for each row and count number of 0s
    // by finding the index of first 1
    int i, index;
 
    for (i = 0; i < R; i++) {
        index = first(mat[i], 0, C - 1);
 
        int cntZeroes = 0;
 
        // If index = -1, that is there is no 1
        // in the row, count of zeroes will be C
        if (index == -1) {
            cntZeroes = C;
        }
 
        // Else, count of zeroes will be index
        // of first 1
        else {
            cntZeroes = index;
        }
 
        // Find max row index
        if (max < cntZeroes) {
            max = cntZeroes;
            max_row_index = i;
        }
 
        // Find min row index
        if (min > cntZeroes) {
            min = cntZeroes;
            min_row_index = i;
        }
    }
 
    cout << "Row with min 0s: " << min_row_index + 1;
    cout << "\nRow with max 0s: " << max_row_index + 1;
}
 
// Driver code
int main()
{
    bool mat[R][C] = { { 0, 0, 0, 1 },
                       { 0, 1, 1, 1 },
                       { 1, 1, 1, 1 },
                       { 0, 0, 0, 0 } };
 
    rowWith0s(mat);
 
    return 0;
}
 
 

Java




// Java implementation of the approach
import java.io.*;
 
class GFG
{
     
static int R = 4;
static int C = 4;
 
// Function to find the index of first 1
// in the binary array arr[]
static int first(int arr[], int low, int high)
{
    if (high >= low)
    {
 
        // Get the middle index
        int mid = low + (high - low) / 2;
 
        // Check if the element at middle index is first 1
        if ((mid == 0 || arr[mid - 1] == 0) && arr[mid] == 1)
            return mid;
 
        // If the element is 0, recur for right side
        else if (arr[mid] == 0)
            return first(arr, (mid + 1), high);
 
        // If element is not first 1, recur for left side
        else
            return first(arr, low, (mid - 1));
    }
    return -1;
}
 
// Function to print rows with maximum
// and minimum number of zeroes
static void rowWith0s(int mat[][])
{
    // Initialize max values
    int max_row_index = 0, max = Integer.MIN_VALUE;
 
    // Initialize min values
    int min_row_index = 0, min = Integer.MAX_VALUE;
 
    // Traverse for each row and count number of 0s
    // by finding the index of first 1
    int i, index;
 
    for (i = 0; i < R; i++)
    {
        index = first(mat[i], 0, C - 1);
 
        int cntZeroes = 0;
 
        // If index = -1, that is there is no 1
        // in the row, count of zeroes will be C
        if (index == -1)
        {
            cntZeroes = C;
        }
 
        // Else, count of zeroes will be index
        // of first 1
        else
        {
            cntZeroes = index;
        }
 
        // Find max row index
        if (max < cntZeroes)
        {
            max = cntZeroes;
            max_row_index = i;
        }
 
        // Find min row index
        if (min > cntZeroes)
        {
            min = cntZeroes;
            min_row_index = i;
        }
    }
 
        System.out.println ("Row with min 0s: " + (min_row_index + 1));
        System.out.println ("Row with max 0s: " + (max_row_index + 1));
}
 
// Driver code
public static void main (String[] args)
{
 
    int mat[][] = { { 0, 0, 0, 1 },
                    { 0, 1, 1, 1 },
                    { 1, 1, 1, 1 },
                    { 0, 0, 0, 0 } };
 
    rowWith0s(mat);
 
 
}
}
 
// This code is contributed by ajit.
 
 

Python3




# Python3 implementation of the approach
 
import sys
 
R = 4
C = 4
 
# Function to find the index of first 1
# in the binary array arr[]
def first(arr, low, high) :
 
    if (high >= low) :
 
        # Get the middle index
        mid = low + (high - low) // 2;
 
        # Check if the element at middle index is first 1
        if ((mid == 0 or arr[mid - 1] == 0) and arr[mid] == 1) :
            return mid;
 
        # If the element is 0, recur for right side
        elif (arr[mid] == 0) :
            return first(arr, (mid + 1), high);
 
        # If element is not first 1, recur for left side
        else :
            return first(arr, low, (mid - 1));
     
    return -1;
 
 
# Function to print rows with maximum
# and minimum number of zeroes
def rowWith0s(mat) :
 
    # Initialize max values
    row_index = 0; max = -(sys.maxsize - 1);
 
    # Initialize min values
    min_row_index = 0; min = sys.maxsize;
 
    # Traverse for each row and count number of 0s
    # by finding the index of first 1
     
    for i in range(R) :
         
        index = first(mat[i], 0, C - 1);
 
        cntZeroes = 0;
 
        # If index = -1, that is there is no 1
        # in the row, count of zeroes will be C
        if (index == -1) :
            cntZeroes = C;
 
        # Else, count of zeroes will be index
        # of first 1
        else :
            cntZeroes = index;
 
        # Find max row index
        if (max < cntZeroes) :
            max = cntZeroes;
            max_row_index = i;
         
        # Find min row index
        if (min > cntZeroes) :
            min = cntZeroes;
            min_row_index = i;
 
    print("Row with min 0s:",min_row_index + 1);
    print("Row with max 0s:", max_row_index + 1);
 
 
# Driver code
if __name__ == "__main__" :
 
    mat = [
            [ 0, 0, 0, 1 ],
            [ 0, 1, 1, 1 ],
            [ 1, 1, 1, 1 ],
            [ 0, 0, 0, 0 ]
        ];
 
    rowWith0s(mat);
 
    # This code is contributed by AnkitRai01
 
 

C#




// C# implementation of the approach
using System;    
     
class GFG
{
     
static int R = 4;
static int C = 4;
 
// Function to find the index of first 1
// in the binary array arr[]
static int first(int []arr, int low, int high)
{
    if (high >= low)
    {
 
        // Get the middle index
        int mid = low + (high - low) / 2;
 
        // Check if the element at middle index is first 1
        if ((mid == 0 || arr[mid - 1] == 0) && arr[mid] == 1)
            return mid;
 
        // If the element is 0, recur for right side
        else if (arr[mid] == 0)
            return first(arr, (mid + 1), high);
 
        // If element is not first 1, recur for left side
        else
            return first(arr, low, (mid - 1));
    }
    return -1;
}
 
// Function to print rows with maximum
// and minimum number of zeroes
static void rowWith0s(int [,]mat)
{
    // Initialize max values
    int max_row_index = 0, max = int.MinValue;
 
    // Initialize min values
    int min_row_index = 0, min = int.MaxValue;
 
    // Traverse for each row and count number of 0s
    // by finding the index of first 1
    int i, index;
 
    for (i = 0; i < R; i++)
    {
        index = first(GetRow(mat,i), 0, C - 1);
 
        int cntZeroes = 0;
 
        // If index = -1, that is there is no 1
        // in the row, count of zeroes will be C
        if (index == -1)
        {
            cntZeroes = C;
        }
 
        // Else, count of zeroes will be index
        // of first 1
        else
        {
            cntZeroes = index;
        }
 
        // Find max row index
        if (max < cntZeroes)
        {
            max = cntZeroes;
            max_row_index = i;
        }
 
        // Find min row index
        if (min > cntZeroes)
        {
            min = cntZeroes;
            min_row_index = i;
        }
    }
 
        Console.WriteLine ("Row with min 0s: " + (min_row_index + 1));
        Console.WriteLine ("Row with max 0s: " + (max_row_index + 1));
}
 
public static int[] GetRow(int[,] matrix, int row)
{
    var rowLength = matrix.GetLength(1);
    var rowVector = new int[rowLength];
 
    for (var i = 0; i < rowLength; i++)
    rowVector[i] = matrix[row, i];
 
    return rowVector;
}
 
// Driver code
public static void Main (String[] args)
{
 
    int [,]mat = { { 0, 0, 0, 1 },
                    { 0, 1, 1, 1 },
                    { 1, 1, 1, 1 },
                    { 0, 0, 0, 0 } };
 
    rowWith0s(mat);
 
 
}
}
 
/* This code contributed by PrinciRaj1992 */
 
 

Javascript




<script>
 
// JavaScript implementation of the approach
 
     
var R = 4;
var C = 4;
 
// Function to find the index of first 1
// in the binary array arr
function first(arr , low , high)
{
    if (high >= low)
    {
 
        // Get the middle index
        var mid = low + parseInt((high - low) / 2);
 
        // Check if the element at middle
        // index is first 1
        if ((mid == 0 || arr[mid - 1] == 0) &&
        arr[mid] == 1)
            return mid;
 
        // If the element is 0, recur for right side
        else if (arr[mid] == 0)
            return first(arr, (mid + 1), high);
 
        // If element is not first 1,
        // recur for left side
        else
            return first(arr, low, (mid - 1));
    }
    return -1;
}
 
// Function to print rows with maximum
// and minimum number of zeroes
function rowWith0s(mat)
{
    // Initialize max values
    var max_row_index = 0, max = Number.MIN_VALUE;
 
    // Initialize min values
    var min_row_index = 0, min = Number.MAX_VALUE;
 
    // Traverse for each row and count number of 0s
    // by finding the index of first 1
    var i, index;
 
    for (i = 0; i < R; i++)
    {
        index = first(mat[i], 0, C - 1);
 
        var cntZeroes = 0;
 
        // If index = -1, that is there is no 1
        // in the row, count of zeroes will be C
        if (index == -1)
        {
            cntZeroes = C;
        }
 
        // Else, count of zeroes will be index
        // of first 1
        else
        {
            cntZeroes = index;
        }
 
        // Find max row index
        if (max < cntZeroes)
        {
            max = cntZeroes;
            max_row_index = i;
        }
 
        // Find min row index
        if (min > cntZeroes)
        {
            min = cntZeroes;
            min_row_index = i;
        }
    }
 
        document.write("Row with min 0s: " +
        (min_row_index + 1)+"<br/>");
        document.write("Row with max 0s: " +
        (max_row_index + 1));
}
 
// Driver code
 
    var mat = [ [ 0, 0, 0, 1 ],
                [ 0, 1, 1, 1 ],
                [ 1, 1, 1, 1 ],
                [ 0, 0, 0, 0 ] ];
 
    rowWith0s(mat);
     
// This code contributed by Rajput-Ji
 
</script>
 
 
Output: 
Row with min 0s: 3 Row with max 0s: 4

 

Time Complexity: O(R*logC), as we are using a loop to traverse R times and in each traversal we are calling the function first which will cost O(logC) time as we are using binary search. 

Auxiliary Space: O(1), as we are not using any extra space.



Next Article
Find and remove maximum value in each row of a given Matrix

S

Striver
Improve
Article Tags :
  • DSA
  • Matrix
  • Binary Search
  • binary-representation
Practice Tags :
  • Binary Search
  • Matrix

Similar Reads

  • Minimize the maximum of Matrix whose rows and columns are in A.P
    Given two integers N and M denoting a matrix of size N*M, the task is to form a matrix following the below criteria and make the maximum element as minimum as possible: Elements in each row are in arithmetic progression from left to right.Elements in each column are also in arithmetic progression fr
    7 min read
  • Find maximum of minimums from Layers of Matrix using numbers 1 to N^2
    Given a square matrix of size N*N using numbers 1 to N^2, the task is to find the maximum of minimums of each layer of the matrix. The layers of the matrix are the boundary elements of the sub-matrix starting at (i, i) and ending at (N - i + 1, N - i + 1), where 1<= i<= ceil(N/2). Examples: In
    7 min read
  • Find and remove maximum value in each row of a given Matrix
    Given a matrix mat[][] of size N * M, the task is to find and remove the maximum of each row from the matrix and add the largest among them and return the final sum. Perform these operations till the matrix becomes empty. Examples: Input: M = 3, N = 2, mat[][] = [[1, 2, 4], [3, 3, 1]]Output: 8Explan
    5 min read
  • Find Column with Maximum Zeros in Matrix
    Given a matrix(2D array) M of size N*N consisting of 0s and 1s only. The task is to find the column with the maximum number of 0s. If more than one column exists, print the one which comes first. If the maximum number of 0s is 0 then return -1. Examples: Input: N = 3, M[][] = {{0, 0, 0}, {1, 0, 1},
    5 min read
  • Maximum and Minimum in a square matrix.
    Given a square matrix of order n*n, find the maximum and minimum from the matrix given. Examples: Input : arr[][] = {5, 4, 9, 2, 0, 6, 3, 1, 8}; Output : Maximum = 9, Minimum = 0 Input : arr[][] = {-5, 3, 2, 4}; Output : Maximum = 4, Minimum = -5 Naive Method : We find maximum and minimum of matrix
    10 min read
  • Maximum Number of Ones in Binary Matrix
    Given a binary matrix mat[][] with dimensions m * n, and any square sub-matrix of mat of size len * len has at most k ones. The task is to return the maximum possible number of ones that the matrix mat can have. Example: Input: m = 3, n = 3, len = 2, k = 1Output: 4Explanation: In a 3*3 matrix, no 2*
    8 min read
  • Find alphabet in a Matrix which has maximum number of stars around it
    Given a matrix mat consisting of * and lowercase English alphabets, the task is to find the character which has the maximum number of * around it (including diagonal elements too). If two characters have same maximum count, print lexicographically smallest character. Source: D-E Shaw Interview Exper
    15+ min read
  • Minimum number of steps to convert a given matrix into Diagonally Dominant Matrix
    Given a matrix of order NxN, the task is to find the minimum number of steps to convert given matrix into Diagonally Dominant Matrix. In each step, the only operation allowed is to decrease or increase any element by 1.Examples: Input: mat[][] = {{3, 2, 4}, {1, 4, 4}, {2, 3, 4}} Output: 5 Sum of the
    6 min read
  • Find the row with maximum unique elements in given Matrix
    Given a matrix arr[][] of size N*M The task is to find the index of the row that has the maximum unique elements. If there are multiple rows possible, return the minimum indexed row. Examples: Input: arr[][] = { {1, 2, 3, 4, 5}, {1, 2, 2, 4, 7}, {1, 3, 1, 3, 1} } Output: 0Explanation: Rows 0, 1
    5 min read
  • Find the count of mountains in a given Matrix
    Given a 2D square matrix of size N X N, the task is to count the number of mountains in the matrix. An element in a matrix is said to be a mountain when all the surrounding elements (in all 8 directions) are smaller than the given element. Examples: Input: matrix = { { 4, 5, 6 }, { 2, 1, 3 }, { 7, 8
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences