Binary Search · Pattern 5 of 8
Searching a sorted 2D matrix
Two shapes. A matrix sorted row after row is one long sorted array: binary search the flattened index. A matrix sorted by row and by column is searched by stepping from a corner.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Each row is sorted, and each row starts after the previous one ends
- Rows sorted left to right and columns sorted top to bottom
- A binary matrix whose rows are sorted (0s then 1s)
The template
// rows and columns sorted: start at the top-right corner
boolean searchMatrix(int[][] m, int target) {
int r = 0, c = m[0].length - 1;
while (r < m.length && c >= 0) {
if (m[r][c] == target) return true;
if (m[r][c] > target) c--; // the rest of this column is bigger
else r++; // the rest of this row is smaller
}
return false;
}
// fully sorted (row after row): index k is cell (k / cols, k % cols)
boolean searchFlat(int[][] m, int target) {
int rows = m.length, cols = m[0].length, lo = 0, hi = rows * cols - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2, v = m[mid / cols][mid % cols];
if (v == target) return true;
if (v < target) lo = mid + 1; else hi = mid - 1;
}
return false;
} def search_matrix(m, target): # rows and columns sorted
r, c = 0, len(m[0]) - 1 # start at the top-right corner
while r < len(m) and c >= 0:
if m[r][c] == target:
return True
if m[r][c] > target:
c -= 1 # the rest of this column is bigger
else:
r += 1 # the rest of this row is smaller
return False
def search_flat(m, target): # fully sorted, row after row
rows, cols = len(m), len(m[0])
lo, hi = 0, rows * cols - 1
while lo <= hi:
mid = (lo + hi) // 2
v = m[mid // cols][mid % cols]
if v == target:
return True
if v < target:
lo = mid + 1
else:
hi = mid - 1
return False // rows and columns sorted: start at the top-right corner
bool searchMatrix(const vector<vector<int>>& m, int target) {
int r = 0, c = (int)m[0].size() - 1;
while (r < (int)m.size() && c >= 0) {
if (m[r][c] == target) return true;
if (m[r][c] > target) c--; // the rest of this column is bigger
else r++; // the rest of this row is smaller
}
return false;
}
// fully sorted (row after row): index k is cell (k / cols, k % cols)
bool searchFlat(const vector<vector<int>>& m, int target) {
int rows = m.size(), cols = m[0].size(), lo = 0, hi = rows * cols - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2, v = m[mid / cols][mid % cols];
if (v == target) return true;
if (v < target) lo = mid + 1; else hi = mid - 1;
}
return false;
} // rows and columns sorted: start at the top-right corner
function searchMatrix(m, target) {
let r = 0, c = m[0].length - 1;
while (r < m.length && c >= 0) {
if (m[r][c] === target) return true;
if (m[r][c] > target) c--; // the rest of this column is bigger
else r++; // the rest of this row is smaller
}
return false;
}
// fully sorted (row after row): index k is cell (k / cols, k % cols)
function searchFlat(m, target) {
const rows = m.length, cols = m[0].length;
let lo = 0, hi = rows * cols - 1;
while (lo <= hi) {
const mid = (lo + hi) >>> 1, v = m[Math.floor(mid / cols)][mid % cols];
if (v === target) return true;
if (v < target) lo = mid + 1; else hi = mid - 1;
}
return false;
} The variations
-
1Flatten the matrix
When every row starts after the previous one ends, the matrix is a sorted array of length rows × cols. Map index k to
(k / cols, k % cols)and run the normal search. -
2Step search from a corner
From the top-right, moving left makes values smaller and moving down makes them bigger, so every comparison removes a row or a column: O(m + n). Rows of 0s then 1s work the same way.
Now you solve
Mistakes to avoid
- Starting the step search at the top-left: both directions increase there, so you cannot decide which way to move.
- Using the flattened search on a matrix that is only sorted by row and column: it is not one sorted sequence.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.