Search a 2D Matrix II
Find out whether a number is in a grid whose rows and columns are both sorted, by walking from one corner.
Given an m × n matrix (a grid of numbers with m rows and n columns) and a number targettarget
Example 1
Output: true
Example 2
Output: false
The Idea
Think of a price chart where the prices rise as you read along any row and also as you read down any column. The matrix in Example 1 is such a chart, with 5 rows and 4 columns, numbered from 0. Row 0 reads 1, 4, 7, 11, and col 0 reads 1, 2, 3, 10, 18.
Yet the 20 numbers are not one long sorted list. Row 0 ends with 11, while row 1 starts with 2. So where should a search for 5 begin, if it is to use the sorting and not read all 20 cells?
Try row 0, col 0 first. It holds 1, which is smaller than 5, but going right and going down both lead to bigger numbers. The comparison cannot tell us which way to go. Row 4, col 3 has the same problem the other way round: 26 is too big, and both left and up give smaller numbers.
Now try row 0, col 3, the top-right corner, which holds 11. Going left in row 0 gives smaller numbers, and going down in col 3 gives bigger ones. Since 11 is bigger than 5, every number below it in col 3 is bigger still. None of col 3 can be 5, so the search moves one column left.
The grid labelled "target 5" in the picture follows that walk. The orange path starts at 11, moves left to 7, which is also too big, and left again to 4. Now 4 is too small, and every number left of 4 in row 0 is smaller still, so the walk moves down. It lands on 5 at row 1, col 1.
The grid labelled "target 20" shows a search that fails. The numbers 11, 12, 16 and 17 are all too small, so the teal path goes down col 3 to 26. Then 26, 23 and 21 are too big, so it goes left along row 4 to 18. Since 18 is too small, the next step goes down and leaves the matrix, marked "outside".
So the top-right corner is a cell where one comparison picks the direction. Each comparison rules out a whole row or a whole column, and the path it draws looks like a flight of stairs. That is why this walk is often called a staircase search.
Solution Approach
Reading every cell would also work, only slowly. The staircase walk needs three decisions: where the walk starts, which way each comparison sends it, and when it stops.
Checking every cell
What does the plain search cost? Two loops, one over the rows and one inside it over the columns, read up to m × n cells, all 20 in Example 1. That works, but it ignores the sorting completely. The staircase walk reads at most one cell per row plus one per column.
Choosing the starting corner
Which corner lets one comparison decide? It must be a cell where one way leads to smaller numbers and the other to bigger ones. Row 0, col 3 has that, and the code starts there. Row 4, col 0, holding 18, has it too, with up for smaller and right for bigger, so a walk from the bottom-left works just as well.
Moving after each comparison
Why is it safe to throw away a whole column? The walk only moves left and down, so at any moment the cells still in play are the ones below and to the left of the current cell. If the current value is bigger than target
Knowing when to stop
When can the walk give up? It finishes with true the moment it lands on target
Java Solution
The method searchMatrix
- First, if the matrix has no rows, or its first row has no columns, return false, since there is no cell to read.
- Start at the top-right corner:
is 0 androw iscol , the last column.matrix[0].length - 1 - A
loop runs as long aswhile is inside the matrix androw is 0 or more. Each pass reads the current cell intocol .value - If
equalsvalue , return true. If it is bigger, move one column left withtarget . If it is smaller, move one row down withcol-- .row++ - When the loop ends because the walk left the matrix, return false.
The main
public class SearchA2DMatrixII {
public static boolean searchMatrix(int[][] matrix, int target) {
if (matrix.length == 0 || matrix[0].length == 0) {
return false; // no cells to search
}
int row = 0;
int col = matrix[0].length - 1; // start at the top-right corner
while (row < matrix.length && col >= 0) {
int value = matrix[row][col];
if (value == target) {
return true;
}
if (value > target) {
col--; // the rest of this column is even bigger
} else {
row++; // the rest of this row is even smaller
}
}
return false;
}
public static void main(String[] args) {
int[][] matrix = {
{1, 4, 7, 11},
{2, 5, 8, 12},
{3, 6, 9, 16},
{10, 13, 14, 17},
{18, 21, 23, 26}
};
int[] targets = {5, 20, 11, 18, 1, 26, 0, 30};
for (int target : targets) {
System.out.println("target " + target + ": " + searchMatrix(matrix, target));
}
System.out.println("one cell [[7]], target 7: " + searchMatrix(new int[][] {{7}}, 7));
System.out.println("one row [[1, 3, 5]], target 4: "
+ searchMatrix(new int[][] {{1, 3, 5}}, 4));
System.out.println("empty matrix, target 1: " + searchMatrix(new int[0][0], 1));
}
}
Running it prints:
target 5: true
target 20: false
target 11: true
target 18: true
target 1: true
target 26: true
target 0: false
target 30: false
one cell [[7]], target 7: true
one row [[1, 3, 5]], target 4: false
empty matrix, target 1: false
The lines for targets 5 and 20 match the two examples, true and false. Next come the corners. Target 11 is found on the very first comparison, since it sits at the starting cell. Target 18 at row 4, col 0 is found on the eighth cell read, after the same seven cells that the teal path for target 20 reads before it reaches 18.
The line target 0: falsecoltarget 30: falserow
The last line, empty matrix, target 1: falsematrix[0].lengthArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
Complexity
The cost is the length of the staircase, since each cell on it takes one comparison.
- Time: O(m + n), because each pass of the loop moves down one of the m rows or left past one of the n columns, so at most m + n - 1 cells are read (8 for target 20).
- Space: O(1), because the walk keeps only
,row andcol and never copies the matrix.value
The same staircase walk counts values in