/74. Search a 2D Matrix

74. Search a 2D Matrix

Medium
Arrays53.6% acceptance

Given a 2D integer array grid of dimensions m x n, where each row is sorted in non-decreasing order and the first element of each row is greater than the last element of the previous row, determine if a given integer value exists in grid. Return True if the value exists, otherwise return False. The solution must run in O(log(m * n)) time.

Example 1

Input: grid = [[2,4,6],[9,12,15],[18,21,24]], value = 12

Output: True

Explanation: 12 is present in the second row.

Example 2

Input: grid = [[5,8,10],[13,17,19],[22,25,30]], value = 7

Output: False

Explanation: 7 is not present in the grid.

Constraints

  • 1 <= len(grid) <= 100
  • 1 <= len(grid[0]) <= 100
  • -10000 <= grid[i][j] <= 10000
  • -10000 <= value <= 10000
  • Each row of grid is sorted in non-decreasing order
  • The first element of each row is greater than the last element of the previous row
Python (current runtime)

Case 1

Input: grid = [[-5,-2,0],[3,7,11],[15,20,25]], value = 20

Expected: True

Case 2

Input: grid = [[1,2,3],[6,7,8],[10,12,14]], value = 5

Expected: False

Case 3

Input: grid = [[100]], value = 100

Expected: True

Case 4

Input: grid = [[-10,-5,0],[5,10,15]], value = -10

Expected: True

Case 5

Input: grid = [[1,2,3],[4,5,6],[7,8,9]], value = 9

Expected: True