Find row number of a binary matrix having maximum number of 1s
Last Updated :
24 Apr, 2023
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)
Similar Reads
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 row with maximum and minimum number of zeroes in given Matrix
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
11 min read
Maximum number of ones in a N*N matrix with given constraints
Given two integers [Tex]n [/Tex]and [Tex]x [/Tex], where [Tex]x <= n [/Tex]. Find the maximum number of one's in a [Tex]n * n [/Tex]binary matrix can have such that every sub-matrix of size [Tex]x * x [/Tex]has atleast one cell as zero. Examples: Input:5 3 Output: Maximum number of ones = 24 The
5 min read
Minimum number of 1s present in a submatrix of given dimensions in a Binary Matrix
Given a 2D binary matrix mat[][] of size N Ã M and two integers A, B, the task is to find the least number of 1s present in a submatrix of dimensions A Ã B or B Ã A. Examples: Input: mat[][] = {{1, 1, 1}, {1, 1, 1}, {1, 1, 1}} A = 2, B = 1Output: 2Explanation: Any submatrix of size 2 X 1 or 1 X 2 wi
13 min read
Find pair of rows in a binary matrix that has maximum bit difference
Given a Binary Matrix. The task is to find the pair of row in the Binary matrix that has maximum bit difference Examples: Input: mat[][] = {{1, 1, 1, 1}, {1, 1, 0, 1}, {0, 0, 0, 0}}; Output : (1, 3) Bit difference between row numbers 1 and 3 is maximum with value 4. Bit difference between 1 and 2 is
15 min read
Find maximum path length in a binary matrix
Given a square matrix mat every element of which is either 0 or 1. A value 1 means connected and 0 means not connected. The task is to find the largest length of a path in the matrix after changing atmost one 0 to 1. A path is a 4-directionally connected group of 1s. Examples: Input: mat[][] = {{1,
9 min read
Maximum sub-matrix area having count of 1's one more than count of 0's
Given a N x N binary matrix. The problem is finding the maximum area sub-matrix having a count of 1's one more than count of 0's. Examples: Input : mat[][] = { {1, 0, 0, 1}, {0, 1, 1, 1}, {1, 0, 0, 0}, {0, 1, 0, 1} } Output : 9 The sub-matrix defined by the boundary values (1, 1) and (3, 3). { {1, 0
15 min read
Maximum number of contiguous array elements with same number of set bits
Given an array with n elements. The task is to find the maximum number of contiguous array elements which have the same number of set bits. Examples: Input : arr[] = {14, 1, 2, 32, 12, 10} Output : 3 Elements 1, 2, 32 have same number of set bits and are contiguous. Input : arr[] = {1, 6, 9, 15, 8}
6 min read
Python map function to find row with maximum number of 1's
Given a boolean 2D array, where each row is sorted. Find the row with the maximum number of 1s. Examples: Input: matrix = [[0, 1, 1, 1], [0, 0, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0]] Output: 2 We have existing solution for this problem please refer Find the row with maximum number of 1's. We can solve t
1 min read
Maximize number of 1s by flipping a subarray
Given a binary array, the task is to find the maximum number of 1's in the array with at most one flip of a subarray allowed. A flip operation switches all 0s to 1s and 1s to 0s. Examples: Input : arr[] = [0, 1, 0, 0, 1, 1, 0]Output : 5Explanation: Flip the subarray from index 2 to 3. Array will bec
10 min read