Search a 2D Matrix
medium
arrays
binary-search
matrix
You are given an m x n integer matrix with two properties:
- Each row is sorted in ascending order from left to right.
- The first integer of each row is greater than the last integer of the previous row.
Return true if target appears in the matrix and false otherwise.
Input / output
- Input:
matrix: int[][],target: int - Output:
boolean
Examples
matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]],target = 3returnstrue.matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]],target = 13returnsfalse.matrix = [[1]],target = 1returnstrue.
Constraints
1 <= m, n <= 100-10000 <= matrix[i][j], target <= 10000- The matrix satisfies the two sorting properties above.
Edge cases
- A single-cell matrix.
- Targets smaller than the first cell or larger than the last cell.
Target complexity
- Aim for
O(log(m * n))time andO(1)extra space.
Hints
- Because the rows chain together, the whole matrix behaves like one sorted array.
- Map a flat index
itomatrix[i / n][i % n]to run a single binary search.
Follow-up If only rows (but not the row-boundaries) were sorted, what search strategy would you use instead?
Examples
Example 1
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
Example 2
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false
Example 3
Input: matrix = [[1]], target = 1
Output: true
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.