InterviewPrepKit

Home / Coding / Binary Search

Search a 2D Matrix

medium Original ↗
Solving tips
  • Spot that the two ordering guarantees make the matrix one flat sorted array of length m*n read row by row, so a single binary search applies.
  • Map a flat index k to a cell with matrix[k // n][k % n] (divide by number of COLUMNS n) instead of materializing the array; run textbook binary search over 0..m*n-1.
  • Target O(log(m*n)) time, O(1) space; the two-search version (find row, then search within) is O(log m + log n) which is the same bound.
  • Common pitfall: swapping // and % in the index conversion, or confusing this with Search a 2D Matrix II (sorted rows AND columns but no cross-row chaining), which needs a staircase walk instead.

Problem

You are given an m x n integer matrix with two ordering guarantees:

  1. Each row is sorted in ascending order.
  2. The first value of each row is strictly greater than the last value of the previous row.

Together these mean the whole matrix, read row by row, is one sorted sequence. Given a target integer, return True if it appears in the matrix and False otherwise. The expected solution runs in O(log(m * n)) time.

Examples

  • matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3True 3 is in row 0 ([1,3,5,7]).
  • matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13False 13 falls between 11 and 16 in reading order but is not present.
  • matrix = [[1]], target = 2False A 1×1 matrix without the target.

Constraints

  • 1 <= m, n <= 100
  • -10^4 <= matrix[i][j], target <= 10^4
  • Required time: O(log(m * n)) — a full scan is not the intended answer.

Think about it first

Hint 1 Only one row can possibly contain the target. Which property of the matrix tells you which row that is?
Hint 2 Two binary searches work: first over rows (compare the target against each row's first and last elements), then a standard binary search inside the chosen row. That's O(log m + log n) = O(log(m·n)).
Hint 3 You can also do it with a single binary search: treat the matrix as one flat sorted array of length `m * n`, and convert a flat index `k` to coordinates with `row = k // n`, `col = k % n`.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.