What does it solve?
Search for a target in a matrix with sorted structure. Matrix I: each row is sorted and every row's first value exceeds the previous row's last, so the whole thing is one sorted sequence. Matrix II: rows and columns are each sorted, but rows don't chain together.
Key insight: for I, map a 1-D index idx to cell (idx/cols, idx%cols) and binary search over rows·cols → O(log(mn)). For II, start at the top-right: bigger than target → move left, smaller → move down. Each step drops a row or column → O(m+n).
The core idea
Complexity
Binary search over all m·n cells using the flat-index trick. O(1) space.
The staircase walk eliminates one row or column per step from the top-right. O(1) space.
Examples & edge cases
Step-by-step table
C++ implementation
My Notes
📝Notes✅
Practice this problem