> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/binary-search/240.-search-a-2d-matrix-ii.md).

# 240. Search a 2D Matrix II

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MenIslVzrA02IljSm3N%2F-MenMI_GRp6LK2TkZm3O%2Fimage.png?alt=media\&token=a031ca76-1e9a-4b86-b71c-6afffe67418f)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MenIslVzrA02IljSm3N%2F-MenMM8AZiSDA-X0qUp8%2Fimage.png?alt=media\&token=05fad8f4-5fc4-43c5-ac37-5f7c67c25f13)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MenIslVzrA02IljSm3N%2F-MenMPCtjr7ZflmTU0C9%2Fimage.png?alt=media\&token=0b8d2cfb-418d-4dd5-8989-d26ef5f7bfad)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MenIslVzrA02IljSm3N%2F-MenMTXUSV6ygbq_DauD%2Fimage.png?alt=media\&token=f1e1913b-bb91-4d06-91bd-c0c22797485f)

the idea is to start from the **right top corner (biggest in this row),  so we can conclude:**

**current value == target, return true**

**current value > target, should do col--, or**

**should row++, find next row**

time: O(m+n)

space: O(1)

```java
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int m = matrix.length;
        int n = matrix[0].length;
        int row = 0;
        int col = n - 1;
        
        while (col >= 0 && row < m) {
            if (matrix[row][col] == target) {
                return true;
            } else if (matrix[row][col] > target) {
                col--;
            } else {
                row++;
            }
        }
        return false;
    }
}
```
