The grid matrix has m rows and n columns. Every row is sorted from smallest to largest as you go left to right, and every column is sorted from smallest to largest as you go top to bottom. Return true if target is one of the values in matrix, and false if it is not.
Unlike a grid that reads in order row by row, a row here may start with a smaller value than the one that ends the row above it. Try to do better than looking at every cell.
11 is in the third row, second column.
No cell holds 14. Notice that the third row starts at 7, which is smaller than the 20 that ends the second row, so the rows don't line up into one sorted list.
A single column is just a sorted list, and a value may appear more than once.
Constraints
m == matrix.lengthn == matrix[i].length1 <= m, n <= 300-10⁹ <= matrix[i][j], target <= 10⁹Binary searching every row works in O(m log n), but you can do better. Look for a corner where moving one way only reaches bigger values and moving the other way only reaches smaller ones.
Each row climbs to the right and each column climbs downward. That is all you get. The rows don't chain together: in Example 1 the third row starts at 7, below the 20 that ends the second row. So you can't fold the grid into one sorted list and binary search it.
Time O(m + n)Space O(1)
The full walkthrough and code are part of Premium
true