Algorithms · Visualized
Matrix: Search 2D Matrix
Matrix & 2D
Rotations, traversals, and grid searches on 2D arrays.
In a matrix where each row is sorted left-to-right and each column is sorted top-to-bottom, you can search efficiently by starting at the top-right corner: if the current value is bigger than the target, move left (eliminate a column); if smaller, move down (eliminate a row). Time: O(rows + cols) average, O(rows + cols), a big improvement over O(rows × cols) brute force worst; space: O(1).
Big-O: Classic O(m·n) sweeps and in-place tricks.
Search a 2D Sorted Matrix
Matrix / 2D ArrayIn a matrix where each row is sorted left-to-right and each column is sorted top-to-bottom, you can search efficiently by starting at the top-right corner: if the current value is bigger than the target, move left (eliminate a column); if smaller, move down (eliminate a row). This eliminates one full row or column at each step.
How Search 2D Matrix Works
- Start at the top-right corner of the matrix (row 0, last column).
- Compare the value at the current position with the target.
- If they're equal, you found it — return the position.
- If the current value is greater than the target, move one column to the left (that column can't contain the target in this row or below... actually eliminates this column for rows below since values only grow downward).
- If the current value is less than the target, move one row down. Repeat until you find the target or move outside the matrix bounds (not found).
Search 2D Matrix Worked Example
Input: {matrix: [[1, 4, 7, 11], [2, 5, 8, 12], [3, 6, 9, 16], [10, 13, 14, 17]], target: 5}
Start at (0,3)=11: 11>5 → move left. (0,2)=7: 7>5 → move left. (0,1)=4: 4<5 → move down. (1,1)=5: match! Found at row1, col1.
def search_2d(m, target):
rows, cols = len(m), len(m[0])
lo, hi = 0, rows * cols - 1
while lo <= hi:
mid = (lo + hi) // 2
v = m[mid // cols][mid % cols]
if v == target:
return True
if v < target:
lo = mid + 1
else:
hi = mid - 1
return FalseBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Search 2D Matrix Time & Space Complexity
When to Use Search 2D Matrix
- Searching sorted grid-like data such as spreadsheets, sorted matrices of scores, or lookup tables.
- A neat example of using structural sorting properties (both rows and columns sorted) to eliminate large chunks of search space at once.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.