Search a 2D Matrix
A medium Matrix interview guide. Task statement, worked examples, intuition, and step-by-step solutions.
- Topic
- Matrix
- Sheets
- 2
- Core for
- 10 roles
The problem
Given an m-by-n matrix where each row and column is sorted in ascending order, determine whether a target value exists in the matrix.
Example 1
- Input
- matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5
- Output
- true
- Why
- The value 5 is found at row 1, column 1.
Example 2
- Input
- matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20
- Output
- false
- Why
- The value 20 is not present in the matrix.
Constraints
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 300
- -10^9 <= matrix[i][j] <= 10^9
- All rows and columns are sorted in ascending order
How to think about it
Updated 2026-09-29Starting at the top-right corner, each comparison eliminates either a row or a column. If the current value exceeds the target, the entire column to the right is useless, so move left. If it is smaller, the entire row above is useless, so move down.
Approaches, worst first
Scan every cell
time O(m*n) · space O(1)
Check each element against the target, ignoring the sorted structure entirely. Every cell gets visited regardless of what the target is or where it might be.
Staircase from top-right
time O(m+n) · space O(1)
Start at the top-right corner. If the current value is larger than the target, move left to discard the current column. If smaller, move down to discard the current row. Each step eliminates one row or one column.
Binary search per rowWrite this one
time O(m log n) · space O(1)
For each row, perform binary search for the target since rows are sorted. Easier to reason about than the staircase, at the cost of an extra logarithmic factor per row. Still beats scanning everything.
Where people lose marks · 3
- Starting at any corner other than top-right or bottom-left breaks the elimination invariant. Both neighbors could be larger or both smaller, making the direction of movement ambiguous at every step.
- The staircase only works because rows are sorted AND columns are sorted independently. If only rows are sorted or columns are sorted, moving in one direction might skip the target.
- The loop must terminate when row exceeds m-1 or column drops below 0, not when a specific cell is found. A target not in the matrix causes the index to walk off the edge.
Full solution
Binary search per row: each row is sorted, so a range check plus one binary search settles whether the target can be in it, giving O(m log n) with nothing to reason about beyond a standard binary search.
Python
from bisect import bisect_left
def search_matrix(matrix: list[list[int]], target: int) -> bool:
for row in matrix:
# rows are sorted, so a binary search answers "is target in this row"
if not row or target < row[0] or target > row[-1]:
continue
i = bisect_left(row, target)
if i < len(row) and row[i] == target:
return True
return False
JavaScript
function searchMatrix(matrix, target) {
for (const row of matrix) {
// rows are sorted, so a binary search answers "is target in this row"
if (row.length === 0 || target < row[0] || target > row[row.length - 1]) continue;
let lo = 0;
let hi = row.length - 1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (row[mid] === target) return true;
if (row[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
}
return false;
}
The theory behind it
Matrix — the ground this problem stands on. All Matrix problems
What Matrix is
A matrix is a flat grid of cells laid out in rows and columns, like a checkerboard or a spreadsheet. Each cell has an address made of two numbers: its row index going down and its column index going across. Because computer memory stores these rows one after another or as arrays of arrays, jumping straight to any individual cell takes the same tiny fraction of time no matter where it sits on the board.
When to reach for it
Reach for matrix techniques when the input is a two-dimensional grid, board, or map. Common prompts include walking through a maze, finding connected islands of land in water, rotating an image ninety degrees in place, or reading numbers in a spiral. Words like rows, columns, neighbors, adjacent squares, or diagonal lines are clear signs. It also appears in grid planning where each cell depends on the values above and to the left.
How the pattern works
Think of navigating the grid using directional coordinate offsets. Define row and column step arrays for moving up, down, left, and right. Always check that new row and column indices stay strictly between zero and the board boundaries before reading cell values. For spiral scans, track four boundary lines for top, bottom, left, and right, shrinking them inward after reading each side. When searching connected regions, mark visited cells directly or write a marker value into the cell to avoid looping.
More Matrix problems
Target Roles
Core requirement for 10 roles:
Track in your role's order
Pick your target role and all 370 problems resequence to what that interview actually asks.
Start freeProblem set and role mapping as of .