Open In App

Find row number of a binary matrix having maximum number of 1s

Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary matrix (containing only 0 and 1) of order n×n. All rows are sorted already, We need to find the row number with the maximum number of 1s. Also, find the number 1 in that row. 

Note: in case of a tie, print the smaller row number.

Examples : 

Input : mat[3][3] = {0, 0, 1,
                     0, 1, 1,
                     0, 0, 0}
Output : Row number = 2, MaxCount = 2

Input : mat[3][3] = {1, 1, 1,
                     1, 1, 1,
                     0, 0, 0}
Output : Row number = 1, MaxCount = 3

Basic Approach: Traverse whole of the matrix and for each row find the number of 1 and among all that keep updating the row number with the maximum number of 1. This approach will result in O(n^2) time complexity.

C++




// CPP program to find row with maximum 1
// in row sorted binary matrix
#include<bits/stdc++.h>
#define N 4
using namespace std;
 
// function for finding row with maximum 1
void findMax (int arr[][N])
{
    int row = 0, i, j;
    for (i=0, j=N-1; i<N;i++)
    {
        // find left most position of 1 in a row
        // find 1st zero in a row
        while (arr[i][j] == 1 && j >= 0)
        {
            row = i;
            j--;
        }
    }
    cout << "Row number = " << row+1;
    cout << ", MaxCount = " << N-1-j;
}
 
// driver program
int main()
{
    int arr[N][N] = {0, 0, 0, 1,
                     0, 0, 0, 1,
                     0, 0, 0, 0,
                     0, 1, 1, 1};
    findMax(arr);
    return 0;
}


Java




// Java program to find row with maximum 1
// in row sorted binary matrix
class GFG {
     
    static final int N = 4;
 
    // function for finding row with maximum 1
    static void findMax(int arr[][]) {
         
        int row = 0, i, j;
 
        for (i = 0, j = N - 1; i < N; i++) {
             
            // find left most position of 1 in
            // a row find 1st zero in a row
            while (j >= 0 && arr[i][j] == 1) {
                 
                row = i;
                j--;
            }
        }
         
        System.out.print("Row number = "
                                + (row + 1));
        System.out.print(", MaxCount = "
                               + (N - 1 - j));
    }
     
    // Driver code
    public static void main(String[] args) {
        int arr[][] = {{0, 0, 0, 1},
                       {0, 0, 0, 1},
                       {0, 0, 0, 0},
                       {0, 1, 1, 1}};
        findMax(arr);
    }
}
 
// This code is contributed by Anant Agarwal.


Python3




# python program to find row with
# maximum 1 in row sorted binary
# matrix
 
N = 4
 
# function for finding row with
# maximum 1
def findMax (arr):
    row = 0
    j = N - 1
    for i in range(0, N):
        # find left most position
        # of 1 in a row find 1st
        # zero in a row
        while (arr[i][j] == 1
                     and j >= 0):
            row = i
            j -= 1
         
    print("Row number = " , row + 1,
         ", MaxCount = ", N - 1 - j)
 
# driver program
arr = [ [0, 0, 0, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 0],
        [0, 1, 1, 1] ]
         
findMax(arr)
 
# This code is contributed by Sam007


C#




// C# program to find row with
// maximum 1 in row sorted binary matrix
using System;
 
class GFG {
 
  static int N = 4;
 
  // function for finding row with maximum 1
  static void findMax(int [,]arr)
  {
    int MaxCount = 0;
    int MaxCountRow = 0;
    for (int i = 0; i < N; i++) {
      int count = 0;
      for (int j = 0; j < N; j++) {
        if (arr[i,j] == 1) {
          count++;
        }
      }
      if (count > MaxCount) {
        MaxCountRow = i + 1;
        MaxCount = count;
      }
    }
    Console.Write("Row number = " + MaxCountRow);
    Console.Write(", MaxCount = " + MaxCount);
 
  }
 
  // Driver code
  public static void Main()
  {
    int [,]arr = {{0, 0, 0, 1},
                  {0, 0, 0, 1},
                  {0, 0, 0, 0},
                  {0, 1, 1, 1}};
    findMax(arr);
  }
}
 
// This code is contributed by ajaymakvana.


Javascript




// JavaScript program to find row with maximum 1 in row sorted binary matrix
// function for finding row with maximum 1
function findMax(arr){
    let N = arr.length;
    let MaxCount = 0;
    let MaxCountRow = 0;
    for(let i = 0; i<N; i++){
        let count = 0;
        for(let j = 0; j<N; j++){
            if(arr[i][j] == 1){
                count++;
            }
        }
        if(count > MaxCount){
            MaxCountRow = i+1;
            MaxCount = count;
        }
    }
    console.log("Row number = " + MaxCountRow + ", MaxCount = " + MaxCount);
}
 
// driver program
let arr = [[0,0,0,1],
           [0,0,0,1],
           [0,0,0,0],
           [0,1,1,1]];
findMax(arr);
 
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)


Output

Row number = 4, MaxCount = 3

Time Complexity: O(N^2)

Auxiliary Space: O(1)

Better Approach: We can perform better if we try to apply the binary search for finding the position of the first 1 in each row and as per that we can find the number of 1 from each row as each row is in sorted order. This will result in O(n log (n)) time complexity.

Efficient Approach: Start with the top right corner with index (1, n) and try to go left until you reach the last 1 in that row (jth column), now if we traverse left to that row, we will find 0, so switch to the row just below, with the same column. Now your position will be (2, j) again in the 2nd row if the jth element is 1 try to go left until you find the last 1 otherwise in the 2nd row if jth element is 0 goes to the next row. So Finally say if you are at any ith row and jth column which is the index of last 1 from right in that row, increment i. So now if we have Aij = 0 again increment i otherwise keep decreasing j until you find the last 1 in that particular row. 
Sample Illustration :

Algorithm : 

for (int i=0, j=n-1; i<n;i++)
{
    // find left most position of 1 in a row
    // find 1st zero in a row
    while (arr[i][j]==1) 
    {
        row = i;
        j--;
    }
}
cout << "Row number =" << row+1;
cout << "MaxCount =" << n-j;

Implementation:

C++




// CPP program to find row with maximum 1
// in row sorted binary matrix
#include<bits/stdc++.h>
#define N 4
using namespace std;
 
// function for finding row with maximum 1
void findMax (int arr[][N])
{
    int row = 0, i, j;
    for (i=0, j=N-1; i<N;i++)
    {
        // find left most position of 1 in a row
        // find 1st zero in a row
        while (arr[i][j] == 1 && j >= 0)
        {
            row = i;
            j--;
        }
    }
    cout << "Row number = " << row+1;
    cout << ", MaxCount = " << N-1-j;
}
 
// driver program
int main()
{
    int arr[N][N] = {0, 0, 0, 1,
                     0, 0, 0, 1,
                     0, 0, 0, 0,
                     0, 1, 1, 1};
    findMax(arr);
    return 0;
}


Java




// Java program to find row with maximum 1
// in row sorted binary matrix
class GFG {
     
    static final int N = 4;
 
    // function for finding row with maximum 1
    static void findMax(int arr[][]) {
         
        int row = 0, i, j;
 
        for (i = 0, j = N - 1; i < N; i++) {
             
            // find left most position of 1 in
            // a row find 1st zero in a row
            while (j >= 0 && arr[i][j] == 1) {
                 
                row = i;
                j--;
            }
        }
         
        System.out.print("Row number = "
                                + (row + 1));
        System.out.print(", MaxCount = "
                               + (N - 1 - j));
    }
     
    // Driver code
    public static void main(String[] args) {
        int arr[][] = {{0, 0, 0, 1},
                       {0, 0, 0, 1},
                       {0, 0, 0, 0},
                       {0, 1, 1, 1}};
        findMax(arr);
    }
}
 
// This code is contributed by Anant Agarwal.


Python3




# python program to find row with
# maximum 1 in row sorted binary
# matrix
 
N = 4
 
# function for finding row with
# maximum 1
def findMax (arr):
    row = 0
    j = N - 1
    for i in range(0, N):
        # find left most position
        # of 1 in a row find 1st
        # zero in a row
        while (arr[i][j] == 1
                     and j >= 0):
            row = i
            j -= 1
         
    print("Row number = " , row + 1,
         ", MaxCount = ", N - 1 - j)
 
# driver program
arr = [ [0, 0, 0, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 0],
        [0, 1, 1, 1] ]
         
findMax(arr)
 
# This code is contributed by Sam007


C#




// C# program to find row with maximum
// 1 in row sorted binary matrix
using System;
 
class GFG {
     
    static int N = 4;
 
    // function for finding row with maximum 1
    static void findMax(int [,]arr)
    {
        int row = 0, i, j;
 
        for (i = 0, j = N - 1; i < N; i++) {
             
            // find left most position of 1 in
            // a row find 1st zero in a row
            while (arr[i,j] == 1 && j >= 0)
            {
                row = i;
                j--;
            }
        }
         
        Console.Write("Row number = " + (row + 1));
        Console.Write(", MaxCount = " + (N - 1 - j));
    }
     
    // Driver code
    public static void Main()
    {
        int [,]arr = {{0, 0, 0, 1},
                      {0, 0, 0, 1},
                      {0, 0, 0, 0},
                      {0, 1, 1, 1}};
        findMax(arr);
    }
}
 
// This code is contributed by nitin mittal


PHP




<?php
// PHP program to find
// row with maximum 1
// in row sorted
// binary matrix
$N = 4;
 
 
// function for finding
// row with maximum 1
function findMax ($arr)
{
     
    global $N;
    $row = 0; $i;
    $j=$N - 1;
    for ($i = 0; $i < $N; $i++)
    {
         
        // find left most position
        // of 1 in a row find 1st
        // zero in a row
        while ($arr[$i][$j] == 1 &&
                           $j >= 0)
        {
            $row = $i;
            $j--;
        }
    }
    echo "Row number = " , $row + 1;
    echo ", MaxCount = " , $N - 1 - $j;
}
 
    // Driver Code
    $arr = array(array(0, 0, 0, 1),
                 array(0, 0, 0, 1),
                 array(0, 0, 0, 0),
                 array(0, 1, 1, 1));
    findMax($arr);
 
// This code is contributed by vt_m.
?>


Javascript




<script>
 
 
// Javascript program to find row with maximum 1
// in row sorted binary matrix
var N = 4
 
// function for finding row with maximum 1
function findMax (arr)
{
    var row = 0, i, j;
    for (i=0, j=N-1; i<N;i++)
    {
        // find left most position of 1 in a row
        // find 1st zero in a row
        while (arr[i][j] == 1 && j >= 0)
        {
            row = i;
            j--;
        }
    }
    document.write( "Row number = " + (row+1));
    document.write( ", MaxCount = " + (N-1-j));
}
 
// driver program
var arr = [[0, 0, 0, 1],
                 [0, 0, 0, 1],
                 [0, 0, 0, 0],
                 [0, 1, 1, 1]];
findMax(arr);
 
 
</script>


Output

Row number = 4, MaxCount = 3

Time Complexity: O(N), where N is the number of rows and columns in the given matrix.
Auxiliary Space: O(1)

Using lower bound:

the idea is to use the lower bound function to find the recent occurrence of 1 in the present row just to track the length of 1.

Steps to solve this problem:

1. Initialize a vector ans of size 2 with all elements set to 0.
2. Initialize two integer variables sum and temp to 0.
3. Iterate over each row of the mat matrix as i from 0 to N-1.
       *initialize a and store the lower bound of 1 in it.
       *Set temp to the current value of sum.
       *Update sum variable to the maximum value between sum and N-a.
       *If the value of sum has changed and is greater than the previous value of temp, update the values of ans with the current row index i and N-a.
4. Return the updated vector ans.

Implementation:

C++




// CPP program to find row with maximum 1
// in row sorted binary matrix
#include<bits/stdc++.h>
#define N 4
using namespace std;
 
// function for finding row with maximum 1
void findMax (vector<vector<int>>&mat)
{
    vector<int>ans(2,0);
        int sum=0,temp=0;
        for(int i=0;i<N;i++){
            int a=lower_bound(mat[i].begin(),mat[i].end(),1)-mat[i].begin();
            temp=sum;
            sum=max(sum,N-a);
            if(sum!=temp and sum>temp){
                ans[0]=i;
                ans[1]=N-a;
            }
        }
         
    cout << "Row number = " << ans[0]+1;
    cout << ", MaxCount = " << ans[1];
}
 
// driver program
int main()
{
    vector<vector<int>>mat = {{0, 0, 0, 1},
                              {0, 0, 0, 1},
                              {0, 0, 0, 0},
                              {0, 1, 1, 1}};
    findMax(mat);
    return 0;
}
//This code is contributed by Prateek kumar Singh


Java




// Java program to find row with maximum 1
// in row sorted binary matrix
import java.util.*;
 
class Main {
   
  // function for finding row with maximum 1
    public static void findMax(List<List<Integer>> mat) {
        List<Integer> ans = new ArrayList<>(Arrays.asList(0, 0));
        int sum = 0, temp = 0;
        int N = mat.size();
        for(int i=0; i<N; i++) {
          // Find the index of first occurrence of 1 using binary search
            int a = Collections.binarySearch(mat.get(i), 1);
            if (a < 0) a = -a - 1;
            temp = sum; // Store the previous value of sum in temp variable
            sum = Math.max(sum, N-a);
           
           // If the current sum is greater than the previous sum,
           // update the ans list with current row number and maximum number of 1s
            if (sum != temp && sum > temp) {
                ans.set(0, i);
                ans.set(1, N-a);
            }
        }
        System.out.println("Row number = " + (ans.get(0)+1) + ", MaxCount = " + ans.get(1));
    }
   
  // driver program
    public static void main(String[] args) {
      // Taking input
        List<List<Integer>> mat = new ArrayList<>(Arrays.asList(
            Arrays.asList(0, 0, 0, 1),
            Arrays.asList(0, 0, 0, 1),
            Arrays.asList(0, 0, 0, 0),
            Arrays.asList(0, 1, 1, 1)
        ));
        findMax(mat);
    }
}


Python3




# Python program to find row with maximum 1
# in row sorted binary matrix
from typing import List
 
# function for finding row with maximum 1
def findMax(mat: List[List[int]]) -> None:
    ans = [0, 0]
    sum = 0
    temp = 0
    N = 4
    for i in range(N):
        a = mat[i].index(1) if 1 in mat[i] else N
        temp = sum
        sum = max(sum, N-a)
        if sum != temp and sum > temp:
            ans[0] = i
            ans[1] = N-a
    print("Row number = ", ans[0]+1, end="")
    print(", MaxCount = ", ans[1])
 
# driver program
if __name__ == "__main__":
    mat = [[0, 0, 0, 1],
           [0, 0, 0, 1],
           [0, 0, 0, 0],
           [0, 1, 1, 1]]
    findMax(mat)


C#




// C# program to find row with maximum 1
// in row sorted binary matrix
using System;
using System.Collections.Generic;
 
class MainClass {
    // function for finding row with maximum 1
    static void FindMax(List<List<int>> mat) {
        int[] ans = new int[]{0, 0};
        int sum = 0;
        int temp = 0;
        int N = 4;
        for (int i = 0; i < N; i++) {
            int a = mat[i].IndexOf(1);
            if (a == -1) {
                a = N;
            }
            temp = sum;
            sum = Math.Max(sum, N - a);
            if (sum != temp && sum > temp) {
                ans[0] = i;
                ans[1] = N - a;
            }
        }
        Console.Write("Row number = " + (ans[0]+1));
        Console.Write(", MaxCount = " + ans[1]);
    }
 
    // driver program
    public static void Main() {
        List<List<int>> mat = new List<List<int>> {
            new List<int> {0, 0, 0, 1},
            new List<int> {0, 0, 0, 1},
            new List<int> {0, 0, 0, 0},
            new List<int> {0, 1, 1, 1}
        };
        FindMax(mat);
    }
}
// This code is contributed by shivhack999


Javascript




// JavaScript program to find row with maximum 1
// in row sorted binary matrix
 
// function for finding row with maximum 1
function findMax(mat) {
let ans = [0, 0];
let sum = 0;
let temp = 0;
let N = 4;
for (let i = 0; i < N; i++) {
let a = mat[i].indexOf(1);
if (a == -1) {
a = N;
}
temp = sum;
sum = Math.max(sum, N - a);
if (sum != temp && sum > temp) {
ans[0] = i;
ans[1] = N - a;
}
}
console.log("Row number = ", ans[0] + 1, ", MaxCount = ", ans[1]);
}
 
// driver program
let mat = [[0, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 0],
[0, 1, 1, 1]];
findMax(mat);


Output

Row number = 4, MaxCount = 3

Time Complexity: O(NLogN), where N is the number of rows and columns in the given matrix.
Auxiliary Space: O(1)

This approach is contributed by Prateek Kumar Singh (pkrsingh025)

 



Last Updated : 24 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads