Understanding the Problem
We are given a binary matrix where each row is sorted in non-decreasing order — that means all 0s come before any 1s in every row. Our task is to find the index of the row that contains the maximum number of 1's.
If multiple rows have the same highest number of 1’s, we must return the first such row (the one with the smallest index). If the matrix is empty or has no 1’s at all, we return -1
.
Since rows are sorted, this opens the door for a faster approach than simply scanning each cell — we can use binary search to find the first 1 in each row and calculate the count of 1s from there.
Step-by-Step Solution with Example
Step 1: Take a sample input
matrix = [
[0, 0, 1, 1],
[0, 1, 1, 1],
[0, 0, 0, 1]
]
This matrix has 3 rows. Each row is sorted.
Step 2: Use binary search on each row
For each row, we perform binary search to find the first occurrence of 1. Since the row is sorted, once we know where 1s begin, we can count the number of 1s as number_of_1s = total_columns - index_of_first_1
.
Step 3: Go row by row
- Row 0: Binary search gives first 1 at index 2 → 2 ones
- Row 1: First 1 at index 1 → 3 ones
- Row 2: First 1 at index 3 → 1 one
Row 1 has the most 1s. So, the answer is 1
.
Step 4: Keep track of max count and row index
As we process each row, we store the max count of 1s found so far and update the result row index if we find a row with more 1s.
Edge Cases
- Matrix is empty: Return
-1
- All elements are 0: No 1s found → Return
-1
- All rows have same number of 1s: Return index of the first such row
- First row is full of 1s: We can stop early because no other row can have more 1s
Finally
This problem becomes much simpler once we realize that rows are sorted. Using binary search for each row significantly speeds up our solution compared to brute-force scanning. This solution works efficiently even for large matrices with a time complexity of O(n log m)
, where n
is the number of rows and m
is the number of columns.
For beginners, always look for problem constraints (like sorted rows) that you can exploit using optimized techniques like binary search.
Comments
Loading comments...