Row with Max 1s in Rowwise Sorted

medium

You are given an n x n binary matrix arr — every cell holds a 0 or a 1 — and every row is sorted in non-decreasing order, meaning all the 0s in a row come before all the 1s.

Return the 0-based index of the first row that contains the maximum number of 1s. If the matrix contains no 1s at all, return -1.

Note:

  • The matrix uses 0-based indexing.
  • n denotes both the number of rows and the number of columns.
  • If several rows tie for the maximum, return the smallest row index.

Hints

Each row is sorted, so its 1s are all bunched together at the right end. What does that tell you about counting them?
The number of 1s in a row is the column count minus the index of the first 1. How fast can you locate the first 1 in a sorted row?
Start at the top-right corner: slide left while you see 1s, drop down a row when you see a 0. The column pointer never needs to move right again.

Common doubts

Counting works but reads every cell — O(n²). Sortedness means each row's 1s form a suffix, so the count is cols - firstOneIndex: binary search finds that boundary in O(log n), and the staircase walk amortizes it to O(1) per row.
Return the smaller index — the first such row. Both the binary-search and staircase solutions update the answer only on a strictly larger count, which keeps the earliest row automatically.
Only each row individually — columns carry no ordering guarantee. So flattening the matrix and binary searching the whole thing does not apply here; the structure lives inside each row.

Interview follow-ups

Then any cell could hide a 1, so you must inspect all of them — the O(n²) scan becomes optimal. Sortedness is exactly what buys the speedup, which is why confirming it up front matters.
No. Any row you skip could be the all-1s winner, so every row must be touched at least once. The staircase walk already achieves that lower bound.
Nothing changes — the top-right staircase never uses column order, only row order. The same walk also powers searching for a target value in such a matrix: slide left when too big, drop down when too small.

Fun facts

  • The pointer's path literally draws a staircase: it traces the exact boundary between the matrix's 0-region and 1-region, stepping left and down but never right or up.
  • The top-right start-and-slide trick is the same engine behind searching a row-and-column sorted matrix — master it here and that harder-looking problem falls for free.

Asked at

AmazonMicrosoftAdobeSamsung
Frequently Sometimes Occasionally
Example 1
Input: n = 4, arr = [[0,1,1,1],[0,0,1,1],[1,1,1,1],[0,0,0,0]]
Output: 2
Row 2 holds four 1s — more than any other row.
Example 2
Input: n = 2, arr = [[0,0],[1,1]]
Output: 1
Row 1 has two 1s; row 0 has none.
Example 3
Input: n = 2, arr = [[0,0],[0,0]]
Output: -1
There are no 1s anywhere, so no row qualifies.
Constraints

- 1 <= n <= 10^3 - arr[i][j] is either 0 or 1 - Every row of arr is sorted in non-decreasing order

Solve this problem →