The Runtime Theory
mediumleetcode#binary-search#matrix

Search a 2D Matrix

Search a target in a row and column sorted 2D matrix by treating it as one flattened sorted array and binary searching with index math.

The Runtime Theory Team1 min read
Solve it

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

Sample cases

in[[1,3,5,7],[10,11,16,20],[23,30,34,60]], 3

outtrue

in[[1,3,5,7],[10,11,16,20],[23,30,34,60]], 13

outfalse

in[[1]], 2

outfalse

The machine must find a target in an m×n matrix where each row is sorted and every row's last element is smaller than the next row's first — the whole matrix is one flattened sorted array. The insight: index arithmetic maps a flat index to a cell: row = mid // n, col = mid % n. Run ordinary binary search over 0..m*n-1 and translate at every step.

python
def search_matrix(matrix, target):
    m, n = len(matrix), len(matrix[0])
    lo, hi = 0, m * n - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        val = matrix[mid // n][mid % n]
        if val == target:
            return True
        if val < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return False

Steps: (1) treat the matrix as an array of length m*n, (2) binary search, converting each midpoint with divmod, (3) return on the first exact match.

Time is O(log(m*n)) — one search over the flattened space. Space is O(1).

Trickiest edge cases: a single row or single column — the divmod math still holds because n comes from the real matrix. Watch the division direction: mid // n uses the number of columns, not rows. The row-major layout is what the problem guarantees; if only per-row sorting were guaranteed, this approach would break.

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.