Given a non-empty grid mat consisting of only 0s and 1s, where all the rows are sorted in ascending order, find the index of the row with the maximum number of ones.
Input : mat = [ [1, 1, 1], [0, 0, 1], [0, 0, 0] ]
Output: 0
Explanation: The row with the maximum number of ones is 0 (0 - indexed).
Input: mat = [ [0, 0], [0, 0] ]
Output: -1
Explanation: The matrix does not contain any 1. So, -1 is the answer.
Input : mat = [ [0, 0, 1], [0, 1, 1], [0, 1, 1] ]
The extremely naive approach is to traverse the matrix as usual using nested loops and for every single row count the number of 1’s. Finally, return the row with the maximum no. of 1’s. If multiple rows contain the maximum no. of 1’s, return the row with the minimum index.
cnt_max
initialized with 0 to store the maximum number of 1’s found and index
initialized with -1 to store the row number.cnt_max
and if the current number of 1’s is greater, update cnt_max
with the current no. of 1’s and ‘index’ with the current row index.#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to find the row
with the maximum number of 1's*/
int rowWithMax1s(vector<vector<int>>& mat) {
int n = mat.size();
int m = mat[0].size();
/* Variable to store the
maximum count of 1's found*/
int cnt_max = 0;
/* Variable to store the index
of the row with max 1's*/
int index = -1;
// Traverse the matrix row by row
for (int i = 0; i < n; i++) {
/* Counter for 1's
in the current row*/
int cnt_ones = 0;
/* Count the number of
1's in the current row*/
for (int j = 0; j < m; j++) {
cnt_ones += mat[i][j];
}
/* Update cnt_max and index if current
row has more 1's than previously found*/
if (cnt_ones > cnt_max) {
cnt_max = cnt_ones;
index = i;
}
}
/* Return the index of the row
with the maximum number of 1's*/
return index;
}
};
int main() {
vector<vector<int>> matrix = {{1, 1, 1}, {0, 0, 1}, {0, 0, 0}};
// Create an instance of the Solution class
Solution sol;
// Print the answer
cout << "The row with maximum number of 1's is: " <<
sol.rowWithMax1s(matrix) << '\n';
return 0;
}
import java.util.*;
class Solution {
/* Function to find the row
with the maximum number of 1's*/
public int rowWithMax1s(int[][] mat) {
int n = mat.length;
int m = mat[0].length;
/* Variable to store the
maximum count of 1's found*/
int cnt_max = 0;
/* Variable to store the index
of the row with max 1's*/
int index = -1;
// Traverse the matrix row by row
for (int i = 0; i < n; i++) {
/* Counter for 1's
in the current row*/
int cnt_ones = 0;
/* Count the number of
1's in the current row*/
for (int j = 0; j < m; j++) {
cnt_ones += mat[i][j];
}
/* Update cnt_max and index if current
row has more 1's than previously found*/
if (cnt_ones > cnt_max) {
cnt_max = cnt_ones;
index = i;
}
}
/* Return the index of the row
with the maximum number of 1's*/
return index;
}
public static void main(String[] args) {
int[][] matrix = {{1, 1, 1}, {0, 0, 1}, {0, 0, 0}};
// Create an instance of the Solution class
Solution sol = new Solution();
// Print the answer
System.out.println("The row with maximum number of 1's is: " +
sol.rowWithMax1s(matrix));
}
}
class Solution:
""" Function to find the row
with the maximum number of 1's"""
def rowWithMax1s(self, mat):
n = len(mat)
m = len(mat[0])
""" Variable to store the
maximum count of 1's found"""
cnt_max = 0
""" Variable to store the index
of the row with max 1's"""
index = -1
# Traverse the matrix row by row
for i in range(n):
""" Counter for 1's
in the current row"""
cnt_ones = 0
""" Count the number of
1's in the current row"""
for j in range(m):
cnt_ones += mat[i][j]
""" Update cnt_max and index if current
row has more 1's than previously found"""
if cnt_ones > cnt_max:
cnt_max = cnt_ones
index = i
""" Return the index of the row
with the maximum number of 1's"""
return index
if __name__ == "__main__":
matrix = [[1, 1, 1], [0, 0, 1], [0, 0, 0]]
# Create an instance of the Solution class
sol = Solution()
# Print the answer
print("The row with maximum number of 1's is:", sol.rowWithMax1s(matrix))
class Solution {
/* Function to find the row
with the maximum number of 1's*/
rowWithMax1s(mat) {
let n = mat.length;
let m = mat[0].length;
/* Variable to store the
maximum count of 1's found*/
let cnt_max = 0;
/* Variable to store the index
of the row with max 1's*/
let index = -1;
// Traverse the matrix row by row
for (let i = 0; i < n; i++) {
/* Counter for 1's
in the current row*/
let cnt_ones = 0;
/* Count the number of
1's in the current row*/
for (let j = 0; j < m; j++) {
cnt_ones += mat[i][j];
}
/* Update cnt_max and index if current
row has more 1's than previously found*/
if (cnt_ones > cnt_max) {
cnt_max = cnt_ones;
index = i;
}
}
/* Return the index of the row
with the maximum number of 1's*/
return index;
}
}
const matrix = [[1, 1, 1], [0, 0, 1], [0, 0, 0]];
//Create an instance of Solution class
const sol = new Solution();
// Print the answer
console.log("The row with maximum number of 1's is: " + sol.rowWithMax1s(matrix));
The idea here is to use Binary Search to optimize the brute-force solution where linear search was being used. Since, each row of the given matrix is sorted, Binary Search can be applied on each row to find the Lower Bound
of 1, as lower bound gives the very first index such that element on that index is either equal to 1 or greater than 1. So, total number of 1's in each row can be calculated as: lower bound of 1 subtracted from total number of columns. Do the same of each row and return the index of row having maximum 1's or in case of multiple rows having maximum 1's, return the smallest index. Finally, if there is no 1 in the matrix return -1.
cnt_max
initialized with 0 to store the maximum number of 1’s found and index
initialized with -1 to store the row number.cnt_max
and if the current number of 1’s is greater, update cnt_max
with the current no. of 1’s and ‘index’ with the current row index.#include <bits/stdc++.h>
using namespace std;
class Solution {
private:
//Helper function to find the lower bound of 1.
int lowerBound(vector<int> arr, int n, int x) {
int low = 0, high = n - 1;
int ans = n;
while (low <= high) {
int mid = (low + high) / 2;
/* If element at mid is greater than or equal
to x then it counld be a possible answer.*/
if (arr[mid] >= x) {
ans = mid;
//Look for smaller index on the left
high = mid - 1;
}
else {
low = mid + 1;
}
}
//Return the answer
return ans;
}
public:
/* Function to find the row
with the maximum number of 1's*/
int rowWithMax1s(vector<vector<int>>& mat) {
int n = mat.size();
int m = mat[0].size();
/* Variable to store the
maximum count of 1's found*/
int cnt_max = 0;
/* Variable to store the index
of the row with max 1's*/
int index = -1;
//Traverse each row of the matrix
for (int i = 0; i < n; i++) {
// Get the number of 1's
int cnt_ones = m - lowerBound(mat[i], m, 1);
/*If the current count is greater than
maximum, store the index of current row
and update the maximum count.*/
if (cnt_ones > cnt_max) {
cnt_max = cnt_ones;
index = i;
}
}
/* Return the index of the row
with the maximum number of 1's*/
return index;
}
};
int main() {
vector<vector<int>> matrix = {{1, 1, 1}, {0, 0, 1}, {0, 0, 0}};
// Create an instance of the Solution class
Solution sol;
// Print the answer
cout << "The row with maximum number of 1's is: " <<
sol.rowWithMax1s(matrix) << '\n';
return 0;
}
import java.util.*;
class Solution {
// Helper function to find the lower bound of 1.
private int lowerBound(int[] arr, int n, int x) {
int low = 0, high = n - 1;
int ans = n;
while (low <= high) {
int mid = (low + high) / 2;
/* If element at mid is greater than or equal
to x then it counld be a possible answer.*/
if (arr[mid] >= x) {
ans = mid;
// Look for smaller index on the left
high = mid - 1;
} else {
low = mid + 1;
}
}
// Return the answer
return ans;
}
/* Function to find the row
with the maximum number of 1's*/
public int rowWithMax1s(int[][] mat) {
int n = mat.length;
int m = mat[0].length;
/* Variable to store the
maximum count of 1's found*/
int cnt_max = 0;
/* Variable to store the index
of the row with max 1's*/
int index = -1;
// Traverse each row of the matrix
for (int i = 0; i < n; i++) {
// Get the number of 1's
int cnt_ones = m - lowerBound(mat[i], m, 1);
/* If the current count is greater than
maximum, store the index of current row
and update the maximum count.*/
if (cnt_ones > cnt_max) {
cnt_max = cnt_ones;
index = i;
}
}
/* Return the index of the row
with the maximum number of 1's*/
return index;
}
public static void main(String[] args) {
int[][] matrix = {{1, 1, 1}, {0, 0, 1}, {0, 0, 0}};
// Create an instance of the Solution class
Solution sol = new Solution();
// Print the answer
System.out.println("The row with maximum number of 1's is: " +
sol.rowWithMax1s(matrix));
}
}
class Solution:
# Helper function to find the lower bound of 1.
def lowerBound(self,arr, n, x):
low, high = 0, n - 1
ans = n
while low <= high:
mid = (low + high) // 2
"""If element at mid is greater than or equal
to x then it could be a possible answer."""
if arr[mid] >= x:
ans = mid
# Look for smaller index on the left
high = mid - 1
else:
low = mid + 1
# Return the answer
return ans
""" Function to find the row
with the maximum number of 1's"""
def rowWithMax1s(self, mat):
n = len(mat)
m = len(mat[0])
""" Variable to store the
maximum count of 1's found"""
cnt_max = 0
""" Variable to store the index
of the row with max 1's"""
index = -1
# Traverse each row of the matrix
for i in range(n):
# Get the number of 1's
cnt_ones = m - self.lowerBound(mat[i], m, 1)
""" If the current count is greater than
maximum, store the index of current row
and update the maximum count."""
if cnt_ones > cnt_max:
cnt_max = cnt_ones
index = i
""" Return the index of the row
with the maximum number of 1's"""
return index
if __name__ == "__main__":
matrix = [[1, 1, 1], [0, 0, 1], [0, 0, 0]]
# Create an instance of the Solution class
sol = Solution()
# Print the answer
print("The row with maximum number of 1's is:", sol.rowWithMax1s(matrix))
class Solution {
// Helper function to find the lower bound of 1.
lowerBound(arr, n, x) {
let low = 0, high = n - 1;
let ans = n;
while (low <= high) {
let mid = Math.floor((low + high) / 2);
/* If element at mid is greater than or equal
to x then it could be a possible answer. */
if (arr[mid] >= x) {
ans = mid;
// Look for smaller index on the left
high = mid - 1;
} else {
low = mid + 1;
}
}
// Return the answer
return ans;
}
/* Function to find the row
with the maximum number of 1's */
rowWithMax1s(mat) {
let n = mat.length;
let m = mat[0].length;
/* Variable to store the
maximum count of 1's found */
let cnt_max = 0;
/* Variable to store the index
of the row with max 1's */
let index = -1;
// Traverse each row of the matrix
for (let i = 0; i < n; i++) {
// Get the number of 1's
let cnt_ones = m - this.lowerBound(mat[i], m, 1);
/* If the current count is greater than
maximum, store the index of current row
and update the maximum count. */
if (cnt_ones > cnt_max) {
cnt_max = cnt_ones;
index = i;
}
}
/* Return the index of the row
with the maximum number of 1's */
return index;
}
}
const matrix = [[1, 1, 1], [0, 0, 1], [0, 0, 0]];
// Create an instance of Solution class
const sol = new Solution();
// Print the answer
console.log("The row with maximum number of 1's is: " + sol.rowWithMax1s(matrix));
Q: Why not just count the 1s in each row directly?
A: Counting 1s in each row requires O(n⋅m), where n is the number of rows and m is the number of columns. By leveraging sorting properties, you can reduce the complexity.
Q: What happens if all rows have the same number of 1s?
A: If multiple rows have the same number of 1s, return the smallest row index. Both binary search and column traversal naturally ensure this.
Q: What if the grid is not sorted?
A: If rows are unsorted, sort each row first (O(n⋅mlogm)) and then apply the same logic. Alternatively, scan each row to count 1s directly, which takes O(n⋅m).
Q: Can this logic extend to multidimensional grids?
A: For higher-dimensional grids (e.g., 3D matrices), flatten the grid along one dimension (e.g., rows or columns) and apply the same logic.