VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-row-with-maximum-number-1s/

⇱ Row with max 1s in Sorted Matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Row with max 1s in Sorted Matrix

Last Updated : 17 May, 2026

Given a m * n binary matrix mat[][] consisting of only 1's and 0's. Each row of the array is sorted in non-decreasing order. Find and return the index of the first row that contains the maximum number of 1's. If no such row exists, return -1.

Examples:

Input: mat[][] = [[ 0 0 1 1 ]
                        [0 1 1 1 ]
                        [0 0 1 1  ]
                        [0 0 0 0 ]]
Output: 1
Explanation: row = 1 has maximum number of 1's, that is 3.

Input: mat[][] = [ [ 0 1 1 1 ]
                  [ 0 0 1 1 ]
                        [ 1 1 1 1 ]
                        [ 0 0 0 0 ]]
Output: 2
Explanation: row = 2 has maximum number of 1's, that is 4.

[Naive Approach] Row-wise traversal - O(m * n) Time and O(1) Space:

A simple method is to do a row-wise traversal of the matrix, count the number of 1s in each row, and compare the count with the max. Finally, return the index of the row with a maximum of 1's.


Output
2

[Better Approach] Using Binary Search - O(m * log(n)) Time O(1) Space:

The idea is to take advantage of the fact that each row is sorted. We use binary search (lower_bound )to find the first occurrence of 1 in each row. Once we get this index, the number of 1s in that row is calculated as the total number of columns minus the index of the first 1. We keep track of the row with the maximum count of 1s while traversing all rows.

Working of approach:

Traverse each row and use lower_bound (binary search) to find the first occurrence of 1.

  • Row 0 -> first 1 at index 1 -> count = 4 - 1 = 3
  • Row 1 -> first 1 at index 2 -> count = 4 - 2 = 2
  • Row 2 -> first 1 at index 0 -> count = 4 - 0 = 4
  • Row 3 -> no 1 found → count = 0

Row 2 has the maximum number of 1s, so return index 2.


Output
2

[Expected Approach] Traversal from top-right to outside the grid - O(m + n) Time and O(1) Space:

The idea is to use the sorted property of rows to avoid checking all elements.Start from the top-right cell(row = 0, col = n- 1) and store the ans = -1. If the value in the current cell is 1, update ans with the current row and move left. Otherwise, if the current cell is 0, move to the next row:

  • If mat[row][col] == 1, update ans = row and move left by col = col - 1.
  • Else if mat[row][col] == 0, row = row + 1.

Continue, till we move outside the grid and return ans.

👁 mat_2

Output
2
Comment