Search a 2D Matrix - Problem
You are given an m x n integer matrix matrix with the following two properties:
- Each row is sorted in non-decreasing order.
- The first integer of each row is greater than the last integer of the previous row.
Given an integer target, return true if target is in matrix or false otherwise.
You must write a solution in O(log(m * n)) time complexity.
Input & Output
Example 1 — Basic Search
$
Input:
matrix = [[1,4,7,11],[2,5,8,12],[3,6,9,16],[10,13,14,17]], target = 5
›
Output:
true
💡 Note:
The target 5 exists in the matrix at position [1,1]. The matrix satisfies both properties: rows are sorted and first element of each row is greater than last element of previous row.
Example 2 — Target Not Found
$
Input:
matrix = [[1,4,7,11],[2,5,8,12],[3,6,9,16],[10,13,14,17]], target = 13
›
Output:
true
💡 Note:
The target 13 exists in the matrix at position [3,1]. Even though it's in the last row, binary search efficiently finds it in O(log(m*n)) time.
Example 3 — Target Not Present
$
Input:
matrix = [[1,4,7,11],[2,5,8,12],[3,6,9,16],[10,13,14,17]], target = 15
›
Output:
false
💡 Note:
The target 15 does not exist anywhere in the matrix. Binary search efficiently determines this without checking all elements.
Constraints
- m == matrix.length
- n == matrix[i].length
- 1 ≤ m, n ≤ 100
- -104 ≤ matrix[i][j], target ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input
Sorted matrix with special properties + target value
2
Process
Use binary search treating matrix as 1D array
3
Output
Return true if target found, false otherwise
Key Takeaway
🎯 Key Insight: A sorted matrix with special properties can be searched like a single sorted array using coordinate transformation
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code