The Search a 2D Matrix interview question gives you an m×n matrix where each row is sorted in ascending order, and the first element of each row is greater than the last element of the previous row. Given a target value, determine whether it exists in the matrix. This "sorted matrix" structure allows you to treat the entire matrix as a sorted 1D array and apply binary search.
This problem is asked at Apple, Cisco, Uber, Goldman Sachs, Microsoft, Meta, Amazon, TikTok, Oracle, Google, Bloomberg, and Adobe because it is the canonical demonstration of adapting binary search to a 2D structure. The matrix's property makes it equivalent to a sorted 1D array, enabling O(log(m×n)) binary search — far better than O(m×n) linear scan. It tests spatial reasoning and index arithmetic.
The pattern is binary search on the flattened matrix. Treat the matrix as a 1D array of length m * n. Binary search on indices [0, m*n - 1]. For a mid index k: the corresponding row is k // n and column is k % n. Compare matrix[k//n][k%n] with target. Adjust left/right pointers accordingly. This gives O(log(m×n)) time.
Alternative: row binary search to find the correct row, then column binary search within that row — also O(log m + log n) = O(log(m×n)).
Matrix:
[1, 3, 5, 7]
[10, 11, 16, 20]
[23, 30, 34, 60]
Target = 16. m=3, n=4. Search range [0, 11].
true.k // n (divide by number of COLUMNS), column = k % n.right = m * n - 1.m == 0 or n == 0 first.For the Search a 2D Matrix coding problem, the binary search and matrix interview pattern is the key skill. The index formula (k // n, k % n) is the heart of the solution — practice it until it's automatic. Interviewers at Grab and Coupang often ask the follow-up "Search a 2D Matrix II" (only row-sorted, not globally sorted) — know that it requires the "staircase search" starting from the top-right corner instead of binary search. Practice both variants.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find a Peak Element II | Medium | Solve | |
| Median of a Row Wise Sorted Matrix | Medium | Solve | |
| Count Negative Numbers in a Sorted Matrix | Easy | Solve | |
| Search a 2D Matrix II | Medium | Solve | |
| Leftmost Column with at Least a One | Medium | Solve |