TRT
Sign in
mediumCoreLeetCode#flat index#binary search

Search a 2D matrix

Search a matrix whose rows continue each other in sorted order, as one flat sorted array of m × n elements.

The Runtime Theory Team1 min read
Taught inRotated and two-dimensional dataPro — members onlyBinary search still works when sorted data has been rotated, because one half of any range is always sorted. Sorted grids can be searched as one long array, or with a staircase walk from a corner.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inmatrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3

outtrue

insame matrix, target = 13

outfalse

inmatrix = [[1]], target = 1

outtrue

Each row of an m × n matrix is sorted, and each row's first value is greater than the previous row's last value. Return whether the target is in the matrix, in O(log(m × n)).

Before you code

Read row by row, the matrix is one sorted list of m × n numbers. You don't need to copy it: convert each flat index to a row and column.

Hints

  1. Binary search flat indexes [0, m * n).
  2. Flat index k is matrix[k // n][k % n].
  3. Alternative: binary search the first column to pick the row, then search that row. Same complexity, more boundaries to get right.

Production & complexity notes

When solving Search a 2D matrix on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Rotated and two-dimensional data to reinforce the underlying pattern.

What it practices

Combining index arithmetic with binary search, from Rotated and two-dimensional data.

Not started

Sign in to save your learning progress.

Sign in to save