Search a 2D Matrix
Find a number in a matrix whose rows are sorted and follow on from each other, with one binary search.
Given a matrix of integers with mntargettruetargetfalse
Example 1
Output: true
Example 2
Output: false
The Idea
Think of a long sorted list printed over several lines of a page. Each line is sorted, and each new line starts where the one before it stopped. The matrix in the examples is exactly that: three lines of four numbers.
Read it row by row: 1, 3, 5, 7, then 10, 11, 16, 20, then 23, 30, 34, 60. The rows never overlap, because 10 comes after 7 and 23 comes after 20. So the twelve values form one sorted list. Where would 13 go in it? Between 11 and 16, and that spot is empty, so the answer for Example 2 is false
Finding that spot in a sorted list does not need a look at every value. Look at the middle value first. If it is smaller than target
That raises one question: the list does not exist, only the matrix does. How do we read, say, the value at position 6 of the list? Look at the picture below.
The top shows the matrix, with its rows and columns numbered from 0. Below it, the same values are lined up as one list, with positions 0 to 11. Each row holds 4 values, so positions 0 to 3 come from row 0, positions 4 to 7 from row 1, and positions 8 to 11 from row 2.
Position 6, in orange, holds 16. Dividing 6 by 4 gives 1 with 2 left over: the 1 is the row and the 2 is the column. The orange line at the bottom writes the same calculation with Java's /%
So the search can run over positions of a list that is never built, and turn each position into a row and a column only when it needs a value.
Solution Approach
After a look at why checking every cell is slow, three things need settling: which positions the search covers, how a position becomes a cell, and how each look narrows the range, plus an optional row-first search.
Checking every cell
Why not just look at each value in turn? For the example that is up to 12 looks, and in general up to m × n. A matrix of 1,000 rows and 1,000 columns has a million cells, while halving a million positions needs at most 20 looks.
The range of positions
Which positions can hold targetlohilo <= hi
From a position to a cell
How does a position become a cell? In Java, dividing two int%colsmidmid / colsmid % cols
The divisor is the number of columns, because that is how many positions each row uses up.
Narrowing the range
What happens after each look? The middle position is mid = lo + (hi - lo) / 2(lo + hi) / 2inttargettruelomid + 1himid - 1
Follow Example 2, with targetmidlomidhimidhilohifalse
Searching for the row first
Another way, if you prefer it, takes two smaller searches. First, a binary search over the first value of each row finds the one row whose range could hold target
Java Solution
The method searchMatrix
- First, read the size of the matrix:
isrows andmatrix.length iscols , the length of the first row.matrix[0].length - Set
to 0 andlo tohi , the first and last positions of the list.rows * cols - 1 - A
loop runs as long aswhile . Each pass picks the middle positionlo <= hi and reads itsmid fromvalue .matrix[mid / cols][mid % cols] - If
equalsvalue , returntarget . If it is smaller, movetrue tolo ; otherwise movemid + 1 tohi .mid - 1 - If the loop ends because no positions are left, return
.false
The main
public class SearchA2DMatrix {
public static boolean searchMatrix(int[][] matrix, int target) {
int rows = matrix.length;
int cols = matrix[0].length;
int lo = 0;
int hi = rows * cols - 1; // positions 0 to rows * cols - 1
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
int value = matrix[mid / cols][mid % cols]; // position -> row and column
if (value == target) {
return true;
} else if (value < target) {
lo = mid + 1; // target is in the later positions
} else {
hi = mid - 1; // target is in the earlier positions
}
}
return false;
}
public static void main(String[] args) {
int[][] matrix = {{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}};
int[] targets = {3, 13, 1, 60, 0, 61};
for (int target : targets) {
System.out.println("target " + target + ": " + searchMatrix(matrix, target));
}
System.out.println("one row [[2, 4, 6]], target 6: "
+ searchMatrix(new int[][] {{2, 4, 6}}, 6));
System.out.println("one column [[2], [4], [6]], target 5: "
+ searchMatrix(new int[][] {{2}, {4}, {6}}, 5));
System.out.println("one cell [[9]], target 9: " + searchMatrix(new int[][] {{9}}, 9));
}
}
Running it prints:
target 3: true
target 13: false
target 1: true
target 60: true
target 0: false
target 61: false
one row [[2, 4, 6]], target 6: true
one column [[2], [4], [6]], target 5: false
one cell [[9]], target 9: true
Look at target 60: truelohilo <= hilo < hifalse
The single column line uses a matrix with colskkfalse
The divisor in mid / colsrowsArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
Complexity
The search halves a range of m × n positions, and each look costs the same small amount of work.
- Time: O(log(m × n)), because every pass of the loop drops half of the positions still in range, and turning a position into a cell takes one division and one remainder.
- Space: O(1), because the list of positions is never built: the method keeps only
,lo ,hi andmid .value
If the rows and columns are each sorted, but a row does not continue the one above, the matrix is no longer one sorted list. That version is