Rows and columns increase; find \(target\). A full scan is \(O(mn)\). Each row is sorted, so it admits binary search.
\(bisect\_left\) on every row returns on a hit. Column monotonicity is unused; the cost is \(O(m\log n)\).
The implementation walks rows and searches, in \(O(1)\) extra space, which is short when \(m\) is modest.
Since all elements in each row are sorted in ascending order, we can use binary search to find the first element that is greater than or equal to target for each row, and then check if this element is equal to target. If it equals target, it means the target value has been found, and we directly return true. If it does not equal target, it means all elements in this row are less than target, and we should continue to search the next row.
If all rows have been searched and the target value has not been found, it means the target value does not exist, so we return false.
The time complexity is \(O(m \times \log n)\), where \(m\) and \(n\) are the number of rows and columns in the matrix, respectively. The space complexity is \(O(1)\).
Solution 2: Search from the Bottom Left or Top Right
Thinking
Solution 1 ignores increasing columns and may inspect every row.
From the bottom-left (or top-right): a too-large value moves up and drops that column’s larger suffix; a too-small value moves right and drops that row’s smaller prefix. Each step deletes a row or a column, in \(O(m+n)\).
Here, we start searching from the bottom left corner and move towards the top right direction, comparing the current element matrix[i][j] with target:
If \(\textit{matrix}[i][j] = \textit{target}\), it means the target value has been found, and we directly return true.
If \(\textit{matrix}[i][j] > \textit{target}\), it means all elements in this column from the current position upwards are greater than target, so we should move the \(i\) pointer upwards, i.e., \(i \leftarrow i - 1\).
If \(\textit{matrix}[i][j] < \textit{target}\), it means all elements in this row from the current position to the right are less than target, so we should move the \(j\) pointer to the right, i.e., \(j \leftarrow j + 1\).
If the search ends and the target is still not found, return false.
The time complexity is \(O(m + n)\), where \(m\) and \(n\) are the number of rows and columns in the matrix, respectively. The space complexity is \(O(1)\).