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
Search for a target value in a 2D matrix where each row is sorted and each row starts with a value greater than the previous row's last value. Treat the matrix as a flattened sorted array and use binary search. Convert the mid index to row and column coordinates: row = Math.floor(mid / cols), col = mid % cols. Compare the matrix value at those coordinates with the target and adjust the search range accordingly.
The index-to-coordinate conversion maps a linear mid to the correct row and column without flattening the matrix into a separate array. The sorted property of the matrix allows standard binary search to work across all rows.
Time complexity is O(log(m*n)), space complexity is 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.
