Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get an m × n grid of integers (m rows, n columns) with two promises:
- Each row is sorted from left to right.
- The first number of each row is bigger than the last number of the row above.
Return true if target is somewhere in the grid and false otherwise. Your solution must run in O(log(m·n)) time. Both m and n are at most 100.
Example:
1 3 5 7
10 11 16 20
23 30 34 60With target = 3 the answer is true. With target = 13 it's false: 13 would sit between 11 and 16, and it isn't there.
Start with brute force
Check every cell. That's O(m·n): 10⁴ checks for a 100 × 100 grid. It ignores both promises.
A smarter version scans down the first column to find the row that could hold the target, then scans that row. That's O(m + n), about 200 checks. Better, but still a scan, and the problem asks for logarithmic time.
Building the intuition
Read the example the way you read a page of text: left to right, then down to the next line.
1 3 5 7 10 11 16 20 23 30 34 60That's one sorted list. Promise 1 keeps each row in order, and promise 2 makes each row continue where the last one stopped. So this "2D" problem is secretly Binary Search on a list of m·n = 12 numbers.
You don't want to copy the grid into a list, because that costs O(m·n) time and memory and defeats the point. So ask: if I'm at position i in that long list, which cell is it?
Every row holds n = 4 numbers. Position 6 comes after one full row (positions 0–3) and lands 2 steps into the next. That's row 6 / 4 = 1, column 6 % 4 = 2, and indeed matrix[1][2] = 16. In general:
row = i / n(integer division: how many full rows come beforei)col = i % n(the remainder: how far into that row)
Now run the usual lower-bound search on positions 0 to m·n, reading each value through that conversion.
The optimal approach
- Let
mbe the number of rows,nthe number of columns, andtotal = m·n. - Set
lo = 0andhi = total. Positiontotalis past the end and counts as true. - While
lo < hi:mid = lo + (hi - lo) // 2, and its value ismatrix[mid / n][mid % n].- If that value is
>= target, sethi = mid. Otherwise setlo = mid + 1.
lois the first position whose value is at leasttarget. Returntrueiflo < totaland that cell equalstarget.
The subtle detail: divide by the number of columns, not rows. n is the length of one row, and that's what tells you how many positions to skip per row. With a square grid both work, so the bug hides until a test like a 1 × 5 grid comes along.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m, n = len(matrix), len(matrix[0])
total = m * n
# Read row by row, the grid is one sorted list; position i is cell (i // n, i % n).
# Find the first position whose value is >= target. It always stays in [lo, hi].
lo, hi = 0, total
while lo < hi:
mid = lo + (hi - lo) // 2
if matrix[mid // n][mid % n] >= target: # divide by COLUMNS, not rows
hi = mid # mid might be the answer, so keep it
else:
lo = mid + 1 # mid and everything before it are too small
# lo == total means every value is smaller than target
return lo < total and matrix[lo // n][lo % n] == targetclass Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size(), n = matrix[0].size();
int total = m * n;
// Read row by row, the grid is one sorted list; position i is cell (i / n, i % n).
// Find the first position whose value is >= target. It always stays in [lo, hi].
int lo = 0, hi = total;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (matrix[mid / n][mid % n] >= target) { // divide by COLUMNS, not rows
hi = mid; // mid might be the answer, so keep it
} else {
lo = mid + 1; // mid and everything before it are too small
}
}
// lo == total means every value is smaller than target
return lo < total && matrix[lo / n][lo % n] == target;
}
};class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length, n = matrix[0].length;
int total = m * n;
// Read row by row, the grid is one sorted list; position i is cell (i / n, i % n).
// Find the first position whose value is >= target. It always stays in [lo, hi].
int lo = 0, hi = total;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (matrix[mid / n][mid % n] >= target) { // divide by COLUMNS, not rows
hi = mid; // mid might be the answer, so keep it
} else {
lo = mid + 1; // mid and everything before it are too small
}
}
// lo == total means every value is smaller than target
return lo < total && matrix[lo / n][lo % n] == target;
}
}/**
* @param {number[][]} matrix
* @param {number} target
* @return {boolean}
*/
var searchMatrix = function (matrix, target) {
const m = matrix.length, n = matrix[0].length;
const total = m * n;
// Read row by row, the grid is one sorted list; position i is cell (i / n, i % n).
// Find the first position whose value is >= target. It always stays in [lo, hi].
let lo = 0, hi = total;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (matrix[Math.floor(mid / n)][mid % n] >= target) { // divide by COLUMNS, not rows
hi = mid; // mid might be the answer, so keep it
} else {
lo = mid + 1; // mid and everything before it are too small
}
}
// lo === total means every value is smaller than target
return lo < total && matrix[Math.floor(lo / n)][lo % n] === target;
};Dry run
The example grid, so m = 3, n = 4 and total = 12. Target 3:
| lo | mid | hi | cell (mid / 4, mid % 4) | value | value >= 3? | update |
|---|---|---|---|---|---|---|
| 0 | 6 | 12 | (1, 2) | 16 | Yes | hi = 6 |
| 0 | 3 | 6 | (0, 3) | 7 | Yes | hi = 3 |
| 0 | 1 | 3 | (0, 1) | 3 | Yes | hi = 1 |
| 0 | 0 | 1 | (0, 0) | 1 | No | lo = 1 |
| 1 | 1 | stop |
Position 1 is cell (0, 1), which holds 3. Return true.
Target 13:
| lo | mid | hi | cell | value | value >= 13? | update |
|---|---|---|---|---|---|---|
| 0 | 6 | 12 | (1, 2) | 16 | Yes | hi = 6 |
| 0 | 3 | 6 | (0, 3) | 7 | No | lo = 4 |
| 4 | 5 | 6 | (1, 1) | 11 | No | lo = 6 |
| 6 | 6 | stop |
Position 6 is cell (1, 2), which holds 16, not 13. Return false.
Complexity
- Time: O(log(m·n)). It's binary search over
m·npositions. For a 100 × 100 grid that's about 14 steps. Each step does one division and one remainder, both O(1). - Space: O(1). The flat list is imaginary; we only store
lo,hiandmid.
Edge cases and traps
- Using
minstead ofninmid / nandmid % n. Passes square tests and fails on rectangles. Test a single row and a single column. - Target bigger than everything. The search ends at
lo = total. Checklo < totalbefore you convert it to a cell, or you'll read rowm, which doesn't exist. - One cell.
total = 1: one step and the check. No special case needed. - Two separate searches (row first, then column). That's also O(log m + log n) = O(log(m·n)) and fine. But it's two loops with two sets of boundaries to get right, and it's easy to pick the wrong row when the target is smaller than a row's first element.
Say it in the interview
"Because each row is sorted and starts after the previous row ends, reading the grid row by row gives a single sorted list of m times n numbers. I don't build that list. Position i maps to row i divided by n and column i mod n, where n is the number of columns. I binary search positions 0 to m times n for the first value that's at least the target, then check that it's in bounds and equal to the target. That's O(log of m times n) time and O(1) space."
Follow-ups interviewers ask
- "What if rows are sorted and columns are sorted, but a row doesn't start after the previous one ends?" That's Search a 2D Matrix II. The flat list is no longer sorted. Start at the top-right corner: if the value is too big, move left; if it's too small, move down. Each step removes a row or a column, so it's O(m + n).
- "What if m·n doesn't fit in a 32-bit int?" Use 64-bit
lo,hiandmid. Here m·n is at most 10⁴, sointis fine. - "Return the cell instead of true/false?" Return
[lo / n, lo % n]after the same check.
Practise the same idea
This is Day 37 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free