CodingNodes / Binary Search / Search a 2D Matrix System design Space play · ←→ step · R restart

Problem

You are given a grid of integers matrix and a number target. The grid has two special properties:

  • every row is sorted from smallest to largest, and
  • the first number of each row is bigger than the last number of the row above it.

Return true if target appears somewhere in the grid, otherwise false. Your solution should run in O(log(m · n)) time, where the grid has m rows and n columns.

Constraints

  • 1 ≤ m, n ≤ 100
  • −10⁴ ≤ matrix[i][j], target ≤ 10⁴
  • Each row is sorted, and each row starts above the end of the previous row

Examples: pick one to animate

Solutions

TimeO(log(m·n)) SpaceO(1)

Time: Each step halves the range of m·n positions, so about log₂(m·n) steps.

Space: Only a few integers are stored; the grid is never copied or flattened in memory.

Because each row continues where the one above ended, the grid reads like a single sorted list of m·n numbers. Binary search over positions 0 to m·n−1, and turn a position into a cell with row = pos / n and column = pos % n.