Problem Description
Given an m x n matrix with each row sorted and the first element of each row larger than the last element of the previous row, determine if a given target integer exists in the matrix. The solution must run in O(log(m * n)) time.
Key Insights
- The matrix is essentially a flattened sorted array due to its properties.
- Use binary search to efficiently determine if the target exists.
- Map the 1D binary search index to the corresponding 2D matrix coordinates using division and modulus operations.
- Achieve O(log(m*n)) time complexity by navigating the matrix as if it were a single sorted list.
Space and Time Complexity
Time Complexity: O(log(m * n)) Space Complexity: O(1)
Solution
We can treat the matrix as a flattened sorted list without physically copying the elements. Given the total number of elements = m * n, perform binary search on indices ranging from 0 to (m*n - 1). For any index mid, calculate its corresponding row as mid // n and column as mid % n. Compare the element at matrix[row][col] with the target. If it equals target, return true; if it is less than target, search the right half; otherwise, search the left half.