Search a 2D Matrix

MediumBinary Search · Flattened Matrix🧩 Binary SearchLeetCode #74 ↗Updated

Problem

You are given an m × n integer matrix in which every row is sorted ascending and each row's first value is larger than the previous row's last value. Report whether target occurs in the matrix, in O(log(m·n)) time.
Input[[1,3,5,7],[10,11,16,20], [23,30,34,60]], t=3Outputtrue
Inputsame matrix, t=13Outputfalse

1 ≤ m, n ≤ 100  ·  -104 ≤ matrix[i][j], target ≤ 104  ·  Required: O(log(m·n)).

Try it yourself

Java
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Read the rows back-to-back and you get one sorted array of length m·n. Binary search it directly, converting index i to matrix[i / n][i % n] on the fly.
PatternBinary Search

Instinct Sorted data, a rotated array, or find the min/max X that works where a yes/no test flips only once - halve the search space every step.

Memory hack Find the fence - every candidate reads NO NO NO YES YES, and binary search just walks to where the fence stands.

Open the Binary Search guide →

Approaches

Brute ForceScan Every Cell

Time O(m · n)Space O(1)

Visit each cell with two nested loops and return true on a match. Uses none of the ordering guarantees.

Java
public boolean searchMatrix(int[][] matrix, int target) {
    for (int[] row : matrix) {
        for (int v : row) {
            if (v == target) return true;
        }
    }
    return false;
}

Correct baseline, but throws away all the sortedness.

At a glance

LevelApproachTimeSpace
Brute ForceScan Every CellO(m · n)O(1)
BetterPick the Row, then Binary Search ItO(m + log n)O(1)
OptimalBinary Search as a Virtual 1D ArrayO(log(m·n))O(1)
Common pitfalls
  • Dividing/modding by m instead of n (columns) — wrong cell.
  • Confusing this with LC 240, where rows don't chain — the 1D trick fails there.
  • m · n can overflow for huge matrices — fine here (≤ 104).
Interview tips
  • Point out the “first > previous last” rule is what makes it one sorted list.
  • Write the index mapping (r, c) = (i / n, i % n) before coding.
  • Mention the staircase walk from the top-right (O(m+n)) for the LC 240 variant.
Pattern
Index-mapped binary search → data that is sorted in a known linear order, even if stored in 2D.
My notes saved in this browser