Search a 2D Matrix
Master this topic with zero to advance depth.
Search a 2D Matrix
Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. The matrix has the following properties: Each row is sorted in non-decreasing order. The first integer of each row is greater than the last integer of the previous row.
Examples
Level I: Brute Force
Intuition
Iterate through every row and every column to find the target. This does not take advantage of any sorting.
Detailed Dry Run
Searching for 3 in [[1,3,5...], ...]
- [0][0]: 1
- [0][1]: 3. Found!
Level II: Row-wise Binary Search
Intuition
First, binary search through the first column to find which row could potentially contain the target. Then, perform a binary search within that specific row.
Detailed Dry Run
matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
- Search first column [1, 10, 23] for row where target could be. Matrix[0][0] <= 3 < Matrix[1][0] (10). Row index 0.
- Binary search Row 0 [1,3,5,7] for 3. Found at index 1.
Level III: Optimal (Flattened Binary Search)
Intuition
Treat the entire matrix as a single sorted array of size . We can map a 1D index idx to 2D coordinates using row = idx / n and col = idx % n.
Detailed Dry Run
| Step | L | R | Mid | Row=Mid/4 | Col=Mid%4 | Val | Decision |
|---|---|---|---|---|---|---|---|
| 1 | 0 | 11 | 5 | 1 | 1 | 11 | 11 > 3 → R = 4 |
| 2 | 0 | 4 | 2 | 0 | 2 | 5 | 5 > 3 → R = 1 |
| 3 | 0 | 1 | 0 | 0 | 0 | 1 | 1 < 3 → L = 1 |
| 4 | 1 | 1 | 1 | 0 | 1 | 3 | Found! |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.