Back to Practice
#0251

Search a 2D Matrix

MediumDSA28 min20 XP

Problem

Each matrix row is sorted, and the first value of each row is greater than the last value of the previous row. Return True if target exists.

Why This Matters

This problem connects index math with binary search boundaries, a common source of off-by-one bugs.

Function Signature

def search_matrix(matrix, target):

Examples

Example 1
Inputmatrix = [[1, 3, 5], [7, 9, 11]], target = 9
OutputTrue

Flattened order is [1, 3, 5, 7, 9, 11], so normal binary search works.

Constraints

  • Return the exact requested value.
  • Handle empty or small inputs when the prompt allows them.
  • Prefer the target DSA pattern over brute force when the input can grow.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
Target exists
Inputtarget 9
ExpectedTrue

Binary search maps flat index 4 to row 1, col 1.

Target missing
Inputtarget 8
ExpectedFalse

8 would sit between 7 and 9 but is absent.

Hidden Test Categories
empty matrixsingle rowsingle column