Quick revision
The short answer
Searching a matrix whose rows and columns are both sorted is a binary search problem in disguise: every comparison should throw away cells that cannot hold the target. We start at the top-right corner and move left when the value is too large, crossing out a column, or down when it is too small, crossing out a row. That takes at most m + n comparisons, O(m + n) time, and O(1) space.
The solution
What it costs
| Approach | Time | Extra space | 1,000 by 1,000 matrix |
|---|---|---|---|
| Look at every cell | O(m * n) | O(1) | up to 1,000,000 comparisons |
| Binary search each row | O(m log n) | O(1) | about 10,000 comparisons |
| Staircase from the top-right corner | O(m + n) | O(1) | at most 2,000 comparisons |
What to remember
We searched a matrix sorted along rows and columns from the top-right corner, where the row shrinks to the left and the column grows downwards. A value larger than the target crosses out its column and a smaller one crosses out its row, leaving us on the corner of a smaller matrix, so the search ends within m + n comparisons in O(1) space. The clue to remember is sorted data plus a lookup: ask which one comparison lets you throw away the most cells with certainty, and in a matrix sorted both ways that is the corner where the two orders disagree.
1What it means to search a table sorted in two directions
Think of the multiplication table on a classroom wall. Each row grows as you read from left to right, and each column grows as you read from top to bottom. If someone asked whether 12 appears on a five by five table, you would not read all twenty-five squares; you would glance at a few likely places and soon know. Our problem is that kind of table filled with any numbers, and our job is to choose those few places on purpose.
A matrix is simply a table of numbers in rows and columns. Ours has m rows and n columns, counted from 0 as Java counts array positions. Every row is sorted in ascending order, so each number is at least as large as the one on its left, and every column is sorted too, so each number is at least as large as the one above it. Given a target, we must say whether it is in the matrix, and if so, in which row and column.
We keep one example throughout. Row 0 reads 1, 4, 7, 11, 15; row 1 reads 2, 5, 8, 12, 19; row 2 reads 3, 6, 9, 16, 22; row 3 reads 10, 13, 14, 17, 24; and row 4 reads 18, 21, 23, 26, 30. Column 1, read downwards, is 4, 5, 6, 13, 21, and it only grows. Our target is 13, and the answer is row 3, column 1, written [3, 1]. We will also look for 20, which is absent, and then the answer is [-1, -1], a pair that can never be a real position.
This can feel like a hard search, because the numbers are not in one long sorted line: row 0 ends at 15 and row 1 starts again at 2. The problem is smaller than it looks. We will find one cell from which every comparison throws away a whole row or a whole column, so the search needs at most m + n comparisons, ten here, instead of twenty-five.
Every row grows from left to right and every column grows from top to bottom. The target 13 is in row 3, column 1.
- target
- 13
- answer
- [3, 1]
- size
- 5 rows, 5 columns
1Each row grows to the right and each column grows downwards. The target 13 sits in row 3, column 1, so the answer is [3, 1].
What to assume
- Is the matrix one long sequence, each row starting where the previous one ended?
- Ours is not.
- Can values repeat?
- Yes, and any matching position will do.
- Absent target or empty matrix?
- We return [-1, -1].
- How large?
- Thousands of rows and columns, so we want better than reading every cell.
Let us first find 13 by eye. Row 0 gives 1, 4, 7, 11, 15, no 13. Rows 1 and 2 give no 13 either. In row 3 we read 10 and then 13, and stop: seventeen looks. Did we need them all? As soon as we reached 15, bigger than 13, the cells below 15 were sure to be bigger still. Hold on to that thought; it is the first hint that the order lets us skip cells.
A careful candidate asks a few questions first. Is the matrix one long sequence, each row starting where the previous one ended? Ours is not, and the FAQs cover that kind. Can values repeat? Yes, and any matching position will do. Absent target or empty matrix? We return [-1, -1]. How large? Thousands of rows and columns, so we want better than reading every cell.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise a binary search problem hiding in a grid
When a beginner first reads this question, the word matrix takes over, and the natural reaction is two nested loops over every cell. That is a fine start, and it is our brute force in the next section. Some readers try binary search on the whole matrix as if it were one sorted list, which fails here because 15 ends row 0 and 2 begins row 1. We need another way to use the order.
Let us take the clues in the question one at a time. The first is the word sorted. When data is sorted and we look for a value, one comparison can tell us more than whether this cell is the answer; it can also rule out a whole group of other cells. In a sorted array, comparing with the middle element rules out half the array.
The second clue is that the matrix is sorted in two directions at once. That ties each cell to its whole row and its whole column. Take 15, at the top-right corner. Everything to its left is smaller, because row 0 grows to the right, and everything below it is larger, because column 4 grows downwards. One comparison with 15 says something about eight other cells.
Together the clues point to the binary search pattern, and the name is broader than the version we know on arrays. Binary means two: each comparison splits the remaining candidates into the part that might hold the answer and the part that cannot, and throws the second part away. On a sorted array the split is at the middle; in our matrix it will be at a corner, and a whole row or column will go. The rule to carry to new problems: when data is sorted, ask which single comparison discards the most cells with certainty, and start there.
Two other ideas look similar but do not fit. A breadth-first search, spreading from a cell to its neighbours like ripples on a pond, is the usual grid tool, but it ignores the order and may visit every cell. Binary searching the matrix as one flat list suits a matrix whose rows continue one another, not ours. Binary searching each row uses part of the order, and we meet it next as a middle step.
3The honest first attempt, looking at every cell
The brute force is the first solution anyone would write: look at every cell, row by row, and stop at the target. It is correct, needs no cleverness, and gives us something to measure better versions against. Next to it is a middle step that binary searches each row, since each row on its own is a sorted array.
Let us count. To find 13, searchAll reads rows 0, 1 and 2 completely, fifteen cells, then two cells of row 3, seventeen comparisons; to report 20 absent it reads all twenty-five. For m rows and n columns that is up to m times n comparisons, so the time is O(m * n), read as order m times n, meaning the work grows with the number of cells. The extra memory, called space, is O(1), constant. A 1,000 by 1,000 matrix costs a million comparisons.
Where is the waste? After reading 15 at the end of row 0, we know 13 is smaller, and column 4 grows downwards, so 19, 22, 24 and 30 are all bigger than 13. The scan reads 19 and 22 anyway. The order had already ruled those cells out.
The middle step is better. Binary search looks at the middle of a row and throws away the half that cannot hold the target, so a row of five needs at most three comparisons, and rows 0 to 3 take eleven in all. For m rows that is O(m log n), where log n counts how many times n can be halved before reaching 1, about 10,000 comparisons for the 1,000 by 1,000 matrix.
But it never uses the order down the columns, so every row is searched from scratch as if the rows above had told us nothing. So we ask the question that leads further: is there a cell whose single comparison uses both orders at once?
4Getting to the staircase walk, one observation at a time
We want a cell where too big and too small send us in different directions. Try the top-left corner, 1. Everything to its right and everything below it is bigger, so if 1 is smaller than 13 the target could be either way, and the comparison has not told us where to go. The bottom-right corner, 30, has the same problem turned around.
Now try the top-right corner, 15. Everything to its left is smaller and everything below it is larger, which is the split we wanted. Since 15 is larger than 13, every cell below 15 is larger still, so column 4 cannot hold 13; we cross it out and step left. Had the corner been smaller than the target, every cell to its left would be smaller still, so we would cross out the row and step down.
From the top-left corner every neighbour is larger, so a comparison cannot choose a direction. From the top-right corner it always can.
- target
- 13
- at
- 1, top-left
- right of it
- larger
- below it
- larger
1At the top-left corner, 1 is smaller than 13, but everything to its right and everything below it is larger. The comparison does not tell us which way to go.
- target
- 13
- at
- 15, top-right
- left of it
- smaller
- below it
- larger
2At the top-right corner, 15, the row to its left holds smaller numbers and the column below it holds larger ones, so the two directions disagree.
- target
- 13
- crossed out
- column 4
- now at
- 11, row 0, col 3
315 is larger than 13, so 19, 22, 24 and 30 below it are larger too. The whole of column 4 is crossed out with one comparison, and we step left onto 11.
Here is the question a beginner usually asks. After one step we are no longer at the corner, so why should the trick still work? Look at what is left. With column 4 crossed out, the cells in play are columns 0 to 3, and the cell we stand on, 11, is the top-right corner of that smaller matrix. Every step leaves us on the top-right corner of a smaller matrix, so one rule serves the whole search.
Why can we never cross out the answer by mistake? We drop a column only when our cell, the smallest value still in play in that column, is larger than the target, and we drop a row only when our cell, the largest still in play in that row, is smaller. So every crossed-out cell is certainly wrong, and if the target is anywhere we must reach it. Walking off the bottom or left edge means nothing is left, so the target is absent.
Drawn on paper, the path looks like a staircase going down and to the left, hence the name staircase search. The bottom-left corner works too, with the directions swapped. On the classroom times table you would do the same by instinct: look at the end of a row, decide whether to go along or down, and never look back.
The mistake beginners make most often is starting at the top-left because loops usually start at 0, 0. From there both neighbours are larger, so the code must guess. The starting corner must be one where the row and the column disagree.
5Watching the staircase find 13
The picture plays the search for 13, one comparison per frame, using the values the Java method produced. The compared cell is marked and crossed-out cells are dimmed, so you can watch the part in play shrink from the top and from the right. Check each move against the rule: larger than 13 means move left and a column fades, smaller means move down and a row fades.
The marked cell is being compared with 13. Dimmed cells have been crossed out and are never read again.
- target
- 13
- row
- 0
- col
- 4
- comparisons
- 0
1We start on the top-right corner, row 0 and column 4, which holds 15. Nothing is crossed out yet, and we are looking for 13.
- target
- 13
- row
- 0
- col
- 4
- value
- 15
- comparisons
- 1
2We compare 15, the top-right corner, with 13. It is larger, so everything below it in column 4 is larger too, and we move left.
- target
- 13
- row
- 0
- col
- 3
- value
- 11
- comparisons
- 2
3Column 4 is crossed out. We compare 11 with 13. It is smaller, so everything to its left in row 0 is smaller too, and we move down.
- target
- 13
- row
- 1
- col
- 3
- value
- 12
- comparisons
- 3
4Row 0 is crossed out. We compare 12 with 13. It is smaller again, so the rest of row 1 is smaller as well, and we move down.
- target
- 13
- row
- 2
- col
- 3
- value
- 16
- comparisons
- 4
5Row 1 is crossed out. We compare 16 with 13. It is larger, so the 17 and 26 below it are larger too, and we move left.
- target
- 13
- row
- 2
- col
- 2
- value
- 9
- comparisons
- 5
6Column 3 is crossed out. We compare 9 with 13. It is smaller, so the 3 and 6 to its left are smaller, and we move down.
- target
- 13
- row
- 3
- col
- 2
- value
- 14
- comparisons
- 6
7Row 2 is crossed out. We compare 14 with 13. It is larger, so the 23 below it is larger too, and we move left.
- target
- 13
- row
- 3
- col
- 1
- value
- 13
- comparisons
- 7
8We compare 13 with 13 and they are equal. We return [3, 1] after seven comparisons, without ever reading the dimmed cells.
Let us read the important frames back. First, 15 is larger, so column 4 goes, and 19, 22, 24 and 30 are never read. Then 11 is smaller and row 0 goes, 12 is smaller and row 1 goes, and 16 is larger and column 3 goes. The path changes direction several times, following the shape of the numbers.
At the sixth comparison we stand on 14 in row 3, column 2. It is larger, so column 2 goes and we step left onto 13, which matches, and we return [3, 1]: seven comparisons against seventeen for the scan.
The search for 20 shows how an absent target ends. Its path is 15, 19, 22, 16, 17, 26, 23, 21, 18. At 18, in row 4 and column 0, the value is smaller than 20, so we move down to row 5, outside the matrix, and return [-1, -1] after nine comparisons, within the promised ten.
6The complete Java program
Here is the full program. main runs our example, the target 5, an absent value, the bottom-left corner and an empty matrix, and each comment shows what that line prints.
Let us read search in the order it runs. The first line guards against an empty matrix, and it must come first, because m[0].length on a matrix with no rows throws an ArrayIndexOutOfBoundsException. Then row starts at 0 and col at m[0].length - 1, which puts us on the top-right corner.
The while loop runs while we are inside the matrix: row has not passed the last row and col has not gone below 0. Those are the only ways out, because row only grows and col only shrinks.
Inside, we read the cell into value. If it equals the target we return its position. If it is larger, col-- crosses out the column; if smaller, row++ crosses out the row. Each pass either finishes or makes the matrix smaller.
If the loop ends, we walked off an edge and return [-1, -1]. In main, 13 prints [3, 1], 5 prints [1, 1] and 20 prints [-1, -1]. The value 18, in the bottom-left corner farthest from our start, takes nine comparisons and prints [4, 0]. The empty matrix prints [-1, -1] without entering the loop.
7How much it costs, and the cases at the edges
Let us count on the example first. Each comparison finds the target or moves us one row down or one column left. With five rows and five columns we can make at most 5 + 5 = 10 comparisons before falling off; 13 took seven and 20 took nine. For m rows and n columns that is at most m + n, so the time is O(m + n).
The space is O(1): whatever the size, we keep only row, col and value, and never copy or change the matrix.
| Approach | Time | Extra space | 1,000 by 1,000 matrix |
|---|---|---|---|
| Look at every cell | O(m * n) | O(1) | up to 1,000,000 comparisons |
| Binary search each row | O(m log n) | O(1) | about 10,000 comparisons |
| Staircase from the top-right corner | O(m + n) | O(1) | at most 2,000 comparisons |
The edge cases need very little code. An empty matrix, or empty rows, returns [-1, -1] from the first line. A single row becomes a plain scan from its right end, and a single column a scan downwards. A target smaller than everything, such as 0, walks left along row 0 and falls off after five comparisons; one larger than everything, such as 31, walks down column 4 and falls off the bottom.
The staircase is not always best. For 3 rows and a million columns, binary searching each row costs about 3 times 20 comparisons, while the staircase may need a million. The shape of the matrix can change the best answer.
8Follow-up questions
What if the matrix is sorted as one long sequence, with each row starting after the previous row ends?
Then the matrix is one sorted array of m * n numbers folded into rows, and ordinary binary search works on it. We search positions 0 to m * n - 1, turning position mid into row mid / n and column mid % n; with 4 columns, position 9 is row 2, column 1. That costs O(log(m * n)), better than m + n. The staircase still works there, but wastes the stronger order.
Can we do better than O(m + n) on a matrix sorted only by rows and by columns?
Not in general. Look at the diagonal from the bottom-left to the top-right, 18, 13, 9, 12, 15 in our example. Each sits in a different row and column, so the sorting says nothing about how they compare with each other, and a search may have to look at every one. That forces about min(m, n) comparisons, and on square matrices the staircase is within a small factor of it. When one side is much shorter, binary searching each short line, O(m log n), wins.
How would you count how many values are less than or equal to a target?
The same staircase works from the bottom-left corner. If the cell we stand on is at most the target, every cell above it in that column is smaller still, so we add row + 1 to the count and step right. If it is larger, it cannot count, so we step up. For the target 13 in our example we count 4 cells in column 0, 4 in column 1, 3 in column 2, 2 in column 3 and none in column 4, 13 in all, and the walk takes O(m + n) steps. This walk is the heart of finding the k-th smallest value in such a matrix.
9Conclusion
We searched a matrix sorted along rows and columns from the top-right corner, where the row shrinks to the left and the column grows downwards. A value larger than the target crosses out its column and a smaller one crosses out its row, leaving us on the corner of a smaller matrix, so the search ends within m + n comparisons in O(1) space. The clue to remember is sorted data plus a lookup: ask which one comparison lets you throw away the most cells with certainty, and in a matrix sorted both ways that is the corner where the two orders disagree.
Open with
Let me confirm the setup: every row is ascending left to right and every column ascending top to bottom, but the matrix is not one continuous sorted sequence, so I cannot binary search it as a flat array.
Then, if they want more
I return the row and column of the target, or minus one, minus one if it is absent or the matrix is empty. The brute force reads every cell, O(m times n). Binary searching each row is O(m log n) but ignores the column order. Since the data is sorted, I want each comparison to throw away a region.
The top-right corner allows that: everything to its left is smaller and everything below it is larger. If the corner is bigger than the target, the whole column below is bigger too, so I move left. If it is smaller, the whole row to its left is smaller too, so I move down.
Each move leaves me on the top-right corner of a smaller matrix, so the same rule applies and I never discard the answer. For 13 in the usual example I visit 15, 11, 12, 16, 9, 14 and then 13.
Each step removes a row or a column, so it is at most m plus n steps, O(m plus n) time and constant space, and I check for an empty matrix before reading the first row.
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 45 times in that collection. How it is counted
- Official documentation
- Arrays (Java 21), 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 "Search for a value in a matrix whose rows and columns are sorted.": https://scrivio-interview-library.netlify.app/data-structures/solutions/search-for-a-value-in-a-matrix-whose-rows-and-columns-are-sorted-fcfbf2/