The brute-force solution checks every element in each row sequentially, leading to:
The optimal solution treats the matrix as a flattened sorted array and uses binary search, achieving O(log(m * n)) time complexity:
The “Search a 2D Matrix” problem asks us to efficiently search for a target value in a 2D matrix that has the following sorted properties:
This structure allows us to treat the 2D matrix almost like a 1D sorted array.
Example:
matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]]
, target = 3
true
This problem is a hybrid of matrix traversal and binary search, testing your ability to convert between 2D and 1D indexing. It's frequently asked in coding interviews and serves as a foundation for more complex matrix and search problems.
Because of the matrix’s sorted structure across rows and columns, we can apply a binary search as if the matrix were a single flat array. The total number of elements is m * n
, and we can use math to translate flat indices to 2D coordinates.
m
be the number of rows and n
be the number of columns.left = 0
and right = m * n - 1
.left <= right
:
mid = Math.floor((left + right) / 2)
.mid
to 2D coordinates:
row = Math.floor(mid / n)
col = mid % n
matrix[row][col]
.true
.left = mid + 1
.right = mid - 1
.false
— the target does not exist in the matrix.
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]]
, target = 16
m = 3, n = 4 → total = 12 elements
Initial range: left = 0, right = 11
Time Complexity: O(log(m * n)), where m is rows and n is columns. This is due to binary search over all elements.
Space Complexity: O(1), as the algorithm uses only constant extra memory.
The “Search a 2D Matrix” problem teaches how binary search can be applied beyond 1D arrays by mapping indices across dimensions. This approach is both time-efficient and elegant, making it ideal for large datasets structured in tabular formats.