InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Binary Search

Search a 2D Matrix

medium Original ↗ 00:00

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`.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug