Scrivio Interview library
Binary searchMatrices and gridsReported 16 times · 16 min read · updated 15 November 2026

In a binary matrix whose rows are sorted, find the row with the most 1s.

1What the question asks, told as a bookcase

Picture a bookcase with four shelves. On every shelf the books have been pushed to the right-hand end, packed tightly with no gaps, so each shelf has some empty space on the left and then a solid block of books. Someone asks which shelf holds the most books. You would not count every book. You would look at where each block begins, because a block that begins further to the left must be longer.

Our problem is exactly this bookcase. We are given a matrix, which is a table of numbers arranged in rows and columns, and every number is a 0 or a 1. A 0 is an empty space and a 1 is a book. The question tells us each row is sorted, which here means all the 0s of a row come first and all its 1s come after them, just like the books pushed to the right. We must return the index of the row with the most 1s, counting rows from 0.

We will keep one example, with four rows and five columns. Row 0 is [0, 0, 0, 1, 1], row 1 is [0, 1, 1, 1, 1], row 2 is [0, 0, 1, 1, 1] and row 3 is [0, 1, 1, 1, 1]. Let us count by hand. Row 0 has two 1s, row 1 has four, row 2 has three and row 3 has four. Rows 1 and 3 tie with four.

PictureThe example matrix, four sorted rows

Each row has its 0s first and its 1s after them. The marked cells are the 1s of the two rows that tie for the most.

  1. 00011011110011101111
    row 0
    2 ones
    row 1
    4 ones
    row 2
    3 ones
    row 3
    4 ones
    answer
    row 1

    1Rows 1 and 3 both hold four 1s, more than any other row. We agree to return the first of them, so the answer is row 1.

What to assume

When two rows tie, which one do we return?
We assume the first, row 1 here.
What if no row has a 1, or the matrix is empty?
We return -1, which cannot be a real row index. We also assume every row has the same length, and that the matrix may be a thousand rows of a thousand columns.

Notice something about the counting we just did. In row 2 the first 1 sits at column 2, and the row has five columns, so it holds 5 - 2 = 3 ones. That is true of every row: the number of 1s equals the number of columns minus the column of the first 1. So the problem is smaller than it looks. We never need to count; we only need to know where the 1s begin.

A careful candidate settles a few details first. When two rows tie, which one do we return? We assume the first, row 1 here. What if no row has a 1, or the matrix is empty? We return -1, which cannot be a real row index. We also assume every row has the same length, and that the matrix may be a thousand rows of a thousand columns.

2How to recognise that this is a binary search problem

When a beginner reads this question for the first time, the natural plan is to count. Go through each row, add up its cells, and remember the biggest total. That plan is correct, but it reads the word sorted and then ignores it, and a word the question goes out of its way to mention is rarely there by accident.

So let us take the clues one at a time. The first clue is the phrase rows are sorted. Ask one question of each cell in a row, is this cell a 1? For [0, 0, 1, 1, 1] the answers are no, no, yes, yes, yes, and they flip exactly once. A sequence whose answers flip once from no to yes has a single boundary, and finding a boundary like that is precisely the job of binary search.

Binary search may be a new name, so here is what it means in everyday words. It is how you look up a word in a paper dictionary. You open near the middle, see whether your word comes before or after that page, and throw away the half that cannot contain it, so a thousand pages need only about ten looks. On a sorted row, one look at the middle cell tells us whether the first 1 is at that cell or to its left, or else to its right.

Together these clues point to the binary search pattern. The general rule to carry to new problems is this. When a sorted sequence has a point where a yes or no answer flips, binary search finds that point in about log n looks, where log n is how many times n can be halved. Here the point is the first 1, and the count follows from it.

There is a second, quieter clue. Every row is sorted in the same direction, and we compare rows only to keep the best one. When one look at a single cell can rule out a whole row, a walk from a corner usually beats a binary search on each row, and we will reach that walk by reasoning.

Some patterns look similar but do not fit. One binary search over the whole matrix as a single sorted list would need each row to end below where the next one begins, which is not promised. Sorting the rows by their counts costs more than simply finding the best one.

3The honest first attempt, counting every cell

The honest first attempt is the counting plan, and it is a good start, because it gives us a correct answer to compare against. We walk the rows from top to bottom. For each row we add up its cells, which counts its 1s, since every 1 adds one and every 0 adds nothing. If the count is strictly bigger than the best count so far, this row becomes the best. Strictly bigger, not bigger or equal, is what keeps the first row of a tie.

By hand, row 0 adds up to 2, which beats the starting best of 0, so best becomes row 0. Row 1 adds up to 4, which beats 2, so best becomes row 1. Row 2 adds up to 3, which does not beat 4. Row 3 adds up to 4, which equals 4 but does not beat it, so best stays row 1. The answer is row 1, as expected.

Java
// Brute force: count the 1s of every row cell by cell.
static int rowWithMostOnes(int[][] m) {
int best = -1, bestCount = 0;
for (int row = 0; row < m.length; row++) {
int count = 0;
for (int x : m[row]) count += x; // add every cell of the row
if (count > bestCount) { bestCount = count; best = row; }
}
return best;
}

Now let us count the work. Four rows of five cells means 20 reads, and for m rows and n columns it is m times n reads, so we write the time as O(m x n), read as order m times n. For a thousand by a thousand matrix that is a million reads. The extra memory, called the space, is just a few int variables, so it is O(1), read as constant.

So where is the waste? Look at row 1, [0, 1, 1, 1, 1]. Once we have seen the 1 at column 1, we know for certain that columns 2, 3 and 4 hold 1s too, because the row is sorted. Reading them one by one teaches us nothing new. The brute force spends most of its time confirming what the sorted order has already promised.

4From binary search on each row to the staircase walk

The waste suggests the first improvement. A row's count depends only on where its first 1 is, and the row is sorted, so we can find that place with binary search. Let us work it on row 0, [0, 0, 0, 1, 1]. We keep two markers, lo at 0 and hi at 5, and the first 1 is somewhere from lo to hi, where hi = 5 would mean the row has no 1 at all.

The middle is (0 + 5) / 2 = 2, and cell 2 is a 0, so the first 1 must be to its right and lo becomes 3. The middle is now (3 + 5) / 2 = 4, and cell 4 is a 1, so the first 1 is at 4 or to its left and hi becomes 4. The middle is (3 + 4) / 2 = 3, a 1, so hi becomes 3. Now lo and hi meet at 3, the first 1, and the row has 5 - 3 = 2 ones. Three looks instead of five.

A beginner often asks why we set hi = mid when the middle cell is a 1, and not hi = mid - 1. Let us try mid - 1 and see what we lose. In row 0 the middle cell 3 is a 1 and it is the very first 1. If we moved hi to 2, we would have thrown away the answer itself. When the middle cell is a 1 it may be the first one, so it must stay inside the range we are still searching.

Step throughBinary search finds where the 1s begin in each row

One frame per row. Compared cells are the ones the binary search looked at; the found cell is that row's first 1.

  1. 00011011110011101111
    row
    0
    first 1
    column 3
    count
    5 - 3 = 2
    best
    row 0
    looks
    3

    1Row 0 probes cells 2, 4 and 3. Cell 2 is a 0, so the 1s start further right; cells 4 and 3 are 1s, and the first 1 is column 3, giving 2 ones.

  2. 00011011110011101111
    row
    1
    first 1
    column 1
    count
    5 - 1 = 4
    best
    row 1
    looks
    6

    2Row 1 probes cells 2, 1 and 0. Cell 0 is a 0, so the first 1 is column 1 and the row holds 4 ones, which beats 2.

  3. 00011011110011101111
    row
    2
    first 1
    column 2
    count
    5 - 2 = 3
    best
    row 1
    looks
    8

    3Row 2 probes cells 2 and 1. Cell 1 is a 0 and cell 2 is a 1, so the row holds 3 ones, not more than 4.

  4. 00011011110011101111
    row
    3
    first 1
    column 1
    count
    5 - 1 = 4
    best
    row 1
    looks
    11

    4Row 3 probes cells 2, 1 and 0 and finds 4 ones. That ties with row 1 but does not beat it, so best stays row 1 after 11 looks.

Each row now costs about log n looks, so the whole matrix costs O(m log n). For a thousand by a thousand matrix that is about ten thousand looks instead of a million. But look at the picture again. Rows 2 and 3 were searched from scratch, as if row 1 had never happened.

Here is the observation that takes us further. We do not really need each row's exact count. We only need to know whether a row beats the best row so far. After row 1, the best row has its first 1 at column 1. A later row can beat it only by having a 1 one column further left, at column 0. So for row 2 one single look at column 0 settles everything. It is a 0, so row 2 cannot win, and we move on without searching it at all.

That gives a walk. Keep one column marker, col, starting at the last column, and go down the rows. While the cell at col is a 1, this row has more 1s than every row above, so we record it as best and move col one step left. When we meet a 0, we move down a row and keep col where it is. The path goes only left and down, like a staircase, so it is called the staircase walk.

Why is it correct? After each row, the cells to the right of col are exactly the 1s of the best row so far, and best is the first row that reached that many. A later row moves col only by having a 1 further left, which means strictly more 1s. A row that only ties sees a 0 at col and is passed over, so the first row of a tie is kept. And the cost is easy to see. col can move left at most n times in the whole walk and the row moves down m times, so there are at most m + n steps.

5Watching the staircase walk on the four rows

The picture plays the staircase walk on our four rows. Watch the current cell move left on 1s and down on a 0, never right and never up. Cells marked done are 1s that the walk has counted for the best row, and compared cells are the 0s where the walk turned down.

Step throughThe staircase walk from the top-right corner

The current cell moves left on a 1 and down on a 0. The panel shows the row, the column marker col, the best row so far and how many cells were read.

  1. 00011011110011101111
    row
    0
    col
    4
    best
    -1
    cells read
    0

    1We start in row 0 at the top-right corner, column 4, with best = -1 because no row has been seen yet.

  2. 00011011110011101111
    row
    0
    col
    3
    best
    row 0
    cells read
    1

    2Cell (0, 4) is a 1, so row 0 has at least one 1. best becomes row 0 and col moves left to 3.

  3. 00011011110011101111
    row
    0
    col
    2
    best
    row 0
    cells read
    2

    3Cell (0, 3) is also a 1. best stays row 0, now with at least two 1s, and col moves left to 2.

  4. 00011011110011101111
    row
    1
    col
    2
    best
    row 0
    cells read
    3

    4Cell (0, 2) is a 0, so row 0 has exactly two 1s. We move down to row 1 and keep col at 2.

  5. 00011011110011101111
    row
    1
    col
    1
    best
    row 1
    cells read
    4

    5Cell (1, 2) is a 1, so row 1 has a 1 further left than row 0 had. best becomes row 1 and col moves to 1.

  6. 00011011110011101111
    row
    1
    col
    0
    best
    row 1
    cells read
    5

    6Cell (1, 1) is a 1 too. best stays row 1, now with at least four 1s, and col moves to 0.

  7. 00011011110011101111
    row
    2
    col
    0
    best
    row 1
    cells read
    6

    7Cell (1, 0) is a 0, so row 1 holds exactly four 1s. We move down to row 2, col still 0.

  8. 00011011110011101111
    row
    3
    col
    0
    best
    row 1
    cells read
    7

    8Cell (2, 0) is a 0, so row 2 cannot beat four 1s. One look rules out the whole row, and we move down.

  9. 00011011110011101111
    row
    done
    col
    0
    best
    row 1
    cells read
    8

    9Cell (3, 0) is a 0, so row 3 only ties with row 1. A tie does not replace best, and the rows are finished.

  10. 00011011110011101111
    answer
    row 1
    ones
    4
    cells read
    8 of 20

    10The walk ends with best = row 1. Its 1s are the cells right of col, columns 1 to 4, so it holds 5 - 1 = 4 ones.

Let us read the important frames back. In the first three frames the walk stays in row 0, reading two 1s and then a 0. In the fourth it drops into row 1 at column 2, not at column 4. That is the saving in one move: to beat row 0, row 1 needs a 1 at column 2, so that is the only cell worth testing.

In the eighth and ninth frames rows 2 and 3 are each settled by one look at column 0. Row 3 holds four 1s, as many as row 1, but its cell at column 0 is a 0, so it is passed over, which is exactly how the tie rule is kept. In all, the walk read 8 cells, against 20 for the brute force and 11 for the binary search.

6The complete Java program

Here is the complete program. It holds the staircase walk, which is our answer, and also the binary search version from the middle step, so you can run both and see that they agree. main runs the example, a matrix with no 1s, a case where the last row wins, and a single row of 1s.

Java
public class RowMostOnes {
// Each row is sorted: 0s first, then 1s. Returns the first row with the most 1s, or -1 if there are none.
static int rowWithMostOnes(int[][] m) {
if (m.length == 0 || m[0].length == 0) return -1;
int cols = m[0].length;
int best = -1;
int col = cols - 1; // start at the top-right corner
for (int row = 0; row < m.length; row++) {
while (col >= 0 && m[row][col] == 1) {
col--; // this row has more 1s than any before: go left
best = row;
}
// a 0 at col means this row cannot beat the best: move down
}
return best; // that row has cols - 1 - col ones
}
// The middle step: binary search each row for the index of its first 1 (n if it has none).
static int firstOne(int[] row) {
int lo = 0, hi = row.length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (row[mid] == 1) hi = mid; // the first 1 is here or to the left
else lo = mid + 1; // the first 1 is to the right
}
return lo;
}
static int rowByBinarySearch(int[][] m) {
int best = -1, bestCount = 0;
for (int row = 0; row < m.length; row++) {
int count = m[row].length - firstOne(m[row]);
if (count > bestCount) { bestCount = count; best = row; }
}
return best;
}
public static void main(String[] args) {
int[][] m = {
{0, 0, 0, 1, 1},
{0, 1, 1, 1, 1},
{0, 0, 1, 1, 1},
{0, 1, 1, 1, 1},
};
System.out.println(rowWithMostOnes(m)); // 1
System.out.println(rowByBinarySearch(m)); // 1
System.out.println(rowWithMostOnes(new int[][] {{0, 0}, {0, 0}})); // -1
System.out.println(rowWithMostOnes(new int[][] {{0, 1}, {1, 1}})); // 1
System.out.println(rowWithMostOnes(new int[][] {{1, 1, 1}})); // 0
}
}

Let us read rowWithMostOnes in the order it runs. The first line returns -1 for an empty matrix, because there is no top-right corner to start from. best starts at -1 because no row has won yet, and col starts at cols - 1, the last column.

The for loop visits the rows from top to bottom. Inside it, the while loop is the left part of the staircase. Its condition checks col >= 0 first, and the order matters. If a row is full of 1s, col becomes -1, and reading m[row][-1] would throw an exception, so the bounds check must come before the cell check. Each time the cell is a 1, we move col left and set best to this row.

When the while loop stops, the cell at col is a 0, or col has run off the left edge. Either way this row cannot beat the best, and moving down needs no code, because the for loop moves to the next row anyway. When all rows are done we return best, and the number of 1s in that row is cols - 1 - col.

firstOne is the binary search we did by hand, with hi = row.length standing for a row with no 1s, and rowByBinarySearch uses the same strictly bigger test as the brute force, so it too keeps the first row of a tie.

The program prints 1 and 1 for our example, -1 for the matrix of 0s, 1 for {{0, 1}, {1, 1}} and 0 for the single row of 1s. A tempting slip in the walk is to reset col to the last column at the start of each row. It still gives the right answer, but it throws away everything earlier rows taught us and brings back the m times n cost.

7How much it costs, and the cases at the edges

Let us count on the example first. The staircase read 8 cells: three in row 0, three in row 1 and one each in rows 2 and 3. In general col moves left at most n times, because it never moves right, and each row ends with at most one look at a 0, so there are at most m + n reads. The time is O(m + n). For a thousand by a thousand matrix that is at most two thousand reads.

The space is O(1), because the walk keeps only three numbers, row, col and best, whatever the size of the matrix. The other two approaches also need only a few numbers, so they differ only in time.

Comparing the approaches
ApproachCells read on the exampleTimeExtra space
Count every cell20O(m x n)O(1)
Binary search each row11O(m log n)O(1)
Staircase walk from the top-right8O(m + n)O(1)

Now the edge cases. An empty matrix returns -1 from the first line, and a matrix with no 1s never moves col, so best stays -1. A row full of 1s drives col to -1, and the col >= 0 check then skips every later row, which is right, because no row can beat a full one. Ties keep the first row, because a tying row always meets a 0 at col.

8Follow-up questions

Is the staircase always better than the binary search on each row?

Not always. The staircase costs up to m + n reads and the binary search about m times log n. When the matrix is square or tall, m + n is smaller. But picture ten rows of a million columns. The staircase might walk a million steps left, while ten binary searches need about ten times twenty looks, only two hundred. So for short, very wide matrices the binary search wins, and a strong answer mentions both costs and when each one is smaller.

What changes if the rows are sorted the other way, with the 1s first?

The same idea works in a mirror. Now a row's count is the index of its first 0, so more 1s means the 0s begin further right. We start at the top-left corner, move right while the cell is a 1, recording the row as best each time, and move down when we see a 0. The bound stays O(m + n), and the tie rule is kept in the same way, because a row that only ties meets a 0 exactly where the walk is standing.

9Conclusion

A sorted row is described completely by where its 1s begin. Binary search finds that place in each row in O(m log n), and the staircase walk carries the best column from row to row, moving left on a 1 and down on a 0, for O(m + n) time and O(1) space. The clue to remember is the word sorted next to a count: look for the boundary instead of counting, and ask whether one look can rule out a whole row.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me confirm the details first: each row has its 0s before its 1s, I return the first row on a tie, and I return -1 if there are no 1s.

Then, if they want more

Counting every cell is O(m times n) and ignores the sorting. Because each row is sorted, its count is the number of columns minus the index of its first 1, and I can find that index with binary search, which gives O(m log n). I can do better by sharing information between rows.

I start at the top-right corner with a column pointer. While the cell is a 1, this row has more 1s than every row above, so I record it as best and move left. When I see a 0, this row cannot beat the best, so I move down and keep the column.

The pointer only moves left or down, so it takes at most m plus n steps, O(m + n) time and O(1) space. A tying row meets a 0 at the current column, so the first row of a tie is kept. For a very wide, short matrix the per-row binary search can be cheaper.

About this answer

Last updated
15 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 16 times in that collection. How it is counted
Official documentation
java.util, package documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "In a binary matrix whose rows are sorted, find the row with the most 1s.": https://scrivio-interview-library.netlify.app/data-structures/solutions/in-a-binary-matrix-whose-rows-are-sorted-find-the-row-with-the-m-5afeab/