Imagine you have a perfectly organized 2D matrix where every row is sorted in ascending order, and each row starts with a number greater than the last number of the previous row. This creates a unique property: if you were to "flatten" this matrix into a single array by reading it row by row, the result would be a completely sorted array!
Your task is to determine whether a given target value exists in this specially structured matrix. The catch? You must solve it in O(log(m × n)) time complexity - essentially treating the 2D matrix as if it were a sorted 1D array and using the power of binary search.
Example:
Matrix: [[1,3,5,7],[10,11,16,20],[23,30,34,60]]
Target: 3 → Return true
Target: 13 → Return false
Input & Output
Visualization
Time & Space Complexity
We potentially visit every element in the m×n matrix
Only using a constant amount of extra space for variables
Constraints
- m == matrix.length
- n == matrix[i].length
- 1 ≤ m, n ≤ 100
- -104 ≤ matrix[i][j], target ≤ 104
- Matrix is sorted: Each row sorted in non-decreasing order
- Matrix is structured: First integer of each row > last integer of previous row