Search a 2D Matrix
Write an efficient algorithm that searches for a target value in an m x n integer matrix. The matrix has two properties: each row is sorted in ascending order from left to right, and the first integer of each row is greater than the last integer of the previous row. These properties mean the matrix can be treated as a single flattened sorted array.
The straightforward approach scans the matrix in O(m * n) time. Binary search treats the 2D grid as a 1D sorted array of length m * n. Compute the mid index, then convert it to row and column coordinates: row = mid / n, col = mid % n. Compare the value at that position with the target and narrow the search range accordingly.
The coordinate conversion is the key insight. Division and modulus of the mid index by the number of columns maps the flat index back to the 2D grid. This works because all rows have the same length (n) and the matrix is strictly row-major sorted.
Edge cases include a 1x1 matrix, a single row (becomes standard binary search), a single column, and the target being smaller or larger than all elements.
The coordinate conversion formula (r = mid / n, c = mid % n) works because the matrix is stored in row-major order. The division gives the row index, and the remainder gives the column. This avoids the need for two separate binary searches (first find row, then column). The time complexity O(log(m*n)) is strictly better than O(m + log n) found in some row-first approaches.
Example Input & Output
Target 8 at row 2 col 1.
Target 13 is not in matrix.
Target 3 is at row 0 col 1.
Single element matrix.
Target larger than the only element.
Algorithm Flow

Solution Approach
Treat matrix as flattened sorted array. Binary search with index-to-coordinate conversion.
Time O(log(m*n)), Space O(1).
Best Answers
class Solution {
public boolean solution(int[][] matrix, int target) {
int m = matrix.length, n = matrix[0].length;
int lo = 0, hi = m * n - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
int r = mid / n, c = mid % n;
if (matrix[r][c] == target) return true;
if (matrix[r][c] < target) lo = mid + 1;
else hi = mid - 1;
}
return false;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
