mediumBinary SearchBinary Search

Search a 2D Matrix

mediumTime: O(log(m*n))Space: O(1)

Recognize the pattern

sorted rows and columnssearch in 2D matrixtreat as 1D sorted array

Brute force idea

A straightforward first read of Search a 2D Matrix is this: Linear scan of all m × n elements. Ignores the sorted structure completely. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

Better approach

The real unlock in Search a 2D Matrix comes when you notice this: Treat the 2D matrix as a flattened 1D sorted array. Binary search with index mapping: row = mid / cols, col = mid % cols. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Key invariant

At the center of Search a 2D Matrix is one steady idea: Because the first element of each row is greater than the last element of the previous row, the matrix IS a sorted array when read left-to-right, top-to-bottom. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Watch out for

The trap in Search a 2D Matrix usually looks like this: Doing two binary searches (find row, then find column) — works but is unnecessary. A single binary search on the flattened index is simpler and just as fast. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Binary Search Pattern