Skip to content

Search a 2D Matrix II

MediumBinary Search
Decode it first. Clues, constraints, pattern and plan before any code.

You are given an m x n grid matrix where each row is sorted left to right and each column is sorted top to bottom. Unlike Search a 2D Matrix, a row can start below where the previous row ended, so the grid is not one sorted list. Return true if target is in the grid.

matrix = [[1,  4,  7,  11, 15],
          [2,  5,  8,  12, 19],
          [3,  6,  9,  16, 22],
          [10, 13, 14, 17, 24],
          [18, 21, 23, 26, 30]]
 
target = 5    →  true
target = 20   →  false

Constraints

  • 1 <= m, n <= 300
  • -10^9 <= matrix[i][j], target <= 10^9
  • Every row and every column is sorted in ascending order.