Practice · Binary search · 3 of 5

Search a Sorted Grid

You are given an m × n grid of integers matrix with two properties: each row is sorted in increasing order, and each row's first number is greater than the last number of the row above. So reading the rows one after another gives a single sorted list.

Return true if target is in matrix, and false otherwise, in O(log(m · n)) time.

Example 1

Input
matrix = [[1, 4, 6], [9, 12, 15], [20, 25, 31]], target = 12
Output
true

Example 2

Input
matrix = [[1, 4, 6], [9, 12, 15], [20, 25, 31]], target = 7
Output
false
7 would fall between 6, the end of row 0, and 9, the start of row 1.

Constraints

  • 1 ≤ m, n ≤ 100
  • Every number, and target, is between −10⁴ and 10⁴.