Search a 2D Matrix

Med
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start•← → to step•? all shortcuts

Solution Guide: Search a 2D Matrix

Approach

Treat the matrix as one virtual sorted array of length rows*cols. Use a single binary search with index mapping: row = floor(mid / cols), col = mid % cols. Compare the mapped value to the target.

Complexity Analysis

Time
O(log(m*n))
Space
O(1)

Pattern

Binary Search (Classic)

Why It Works

The entire matrix is effectively one sorted array. Map virtual index to row/col: row = floor(mid / cols), col = mid % cols.

Updated Mar 2026