Find row number of a binary matrix having maximum number of 1s
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++
#include<bits/stdc++.h>
#define N 4
using namespace std;
void findMax ( int arr[][N])
{
int row = 0, i, j;
for (i=0, j=N-1; i<N;i++)
{
while (arr[i][j] == 1 && j >= 0)
{
row = i;
j--;
}
}
cout << "Row number = " << row+1;
cout << ", MaxCount = " << N-1-j;
}
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
class GFG {
static final int N = 4 ;
static void findMax( int arr[][]) {
int row = 0 , i, j;
for (i = 0 , j = N - 1 ; i < N; i++) {
while (j >= 0 && arr[i][j] == 1 ) {
row = i;
j--;
}
}
System.out.print( "Row number = "
+ (row + 1 ));
System.out.print( ", MaxCount = "
+ (N - 1 - j));
}
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);
}
}
|
Python3
N = 4
def findMax (arr):
row = 0
j = N - 1
for i in range ( 0 , N):
while (arr[i][j] = = 1
and j > = 0 ):
row = i
j - = 1
print ( "Row number = " , row + 1 ,
", MaxCount = " , N - 1 - j)
arr = [ [ 0 , 0 , 0 , 1 ],
[ 0 , 0 , 0 , 1 ],
[ 0 , 0 , 0 , 0 ],
[ 0 , 1 , 1 , 1 ] ]
findMax(arr)
|
C#
using System;
class GFG {
static int N = 4;
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);
}
public static void Main()
{
int [,]arr = {{0, 0, 0, 1},
{0, 0, 0, 1},
{0, 0, 0, 0},
{0, 1, 1, 1}};
findMax(arr);
}
}
|
Javascript
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);
}
let arr = [[0,0,0,1],
[0,0,0,1],
[0,0,0,0],
[0,1,1,1]];
findMax(arr);
|
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++
#include<bits/stdc++.h>
#define N 4
using namespace std;
void findMax ( int arr[][N])
{
int row = 0, i, j;
for (i=0, j=N-1; i<N;i++)
{
while (arr[i][j] == 1 && j >= 0)
{
row = i;
j--;
}
}
cout << "Row number = " << row+1;
cout << ", MaxCount = " << N-1-j;
}
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
class GFG {
static final int N = 4 ;
static void findMax( int arr[][]) {
int row = 0 , i, j;
for (i = 0 , j = N - 1 ; i < N; i++) {
while (j >= 0 && arr[i][j] == 1 ) {
row = i;
j--;
}
}
System.out.print( "Row number = "
+ (row + 1 ));
System.out.print( ", MaxCount = "
+ (N - 1 - j));
}
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);
}
}
|
Python3
N = 4
def findMax (arr):
row = 0
j = N - 1
for i in range ( 0 , N):
while (arr[i][j] = = 1
and j > = 0 ):
row = i
j - = 1
print ( "Row number = " , row + 1 ,
", MaxCount = " , N - 1 - j)
arr = [ [ 0 , 0 , 0 , 1 ],
[ 0 , 0 , 0 , 1 ],
[ 0 , 0 , 0 , 0 ],
[ 0 , 1 , 1 , 1 ] ]
findMax(arr)
|
C#
using System;
class GFG {
static int N = 4;
static void findMax( int [,]arr)
{
int row = 0, i, j;
for (i = 0, j = N - 1; i < N; i++) {
while (arr[i,j] == 1 && j >= 0)
{
row = i;
j--;
}
}
Console.Write( "Row number = " + (row + 1));
Console.Write( ", MaxCount = " + (N - 1 - j));
}
public static void Main()
{
int [,]arr = {{0, 0, 0, 1},
{0, 0, 0, 1},
{0, 0, 0, 0},
{0, 1, 1, 1}};
findMax(arr);
}
}
|
PHP
<?php
$N = 4;
function findMax ( $arr )
{
global $N ;
$row = 0; $i ;
$j = $N - 1;
for ( $i = 0; $i < $N ; $i ++)
{
while ( $arr [ $i ][ $j ] == 1 &&
$j >= 0)
{
$row = $i ;
$j --;
}
}
echo "Row number = " , $row + 1;
echo ", MaxCount = " , $N - 1 - $j ;
}
$arr = array ( array (0, 0, 0, 1),
array (0, 0, 0, 1),
array (0, 0, 0, 0),
array (0, 1, 1, 1));
findMax( $arr );
?>
|
Javascript
<script>
var N = 4
function findMax (arr)
{
var row = 0, i, j;
for (i=0, j=N-1; i<N;i++)
{
while (arr[i][j] == 1 && j >= 0)
{
row = i;
j--;
}
}
document.write( "Row number = " + (row+1));
document.write( ", MaxCount = " + (N-1-j));
}
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++
#include<bits/stdc++.h>
#define N 4
using namespace std;
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];
}
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;
}
|
Java
import java.util.*;
class Main {
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++) {
int a = Collections.binarySearch(mat.get(i), 1 );
if (a < 0 ) a = -a - 1 ;
temp = sum;
sum = Math.max(sum, N-a);
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 ));
}
public static void main(String[] args) {
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
from typing import List
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 ])
if __name__ = = "__main__" :
mat = [[ 0 , 0 , 0 , 1 ],
[ 0 , 0 , 0 , 1 ],
[ 0 , 0 , 0 , 0 ],
[ 0 , 1 , 1 , 1 ]]
findMax(mat)
|
C#
using System;
using System.Collections.Generic;
class MainClass {
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]);
}
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);
}
}
|
Javascript
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]);
}
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
Share your thoughts in the comments
Please Login to comment...