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 m rows and n columns, and a number target, return true if target is in the matrix and false if it is not. The matrix has two properties: each row is sorted from left to right, and the first value of each row is greater than the last value of the row above. The solution must run in O(log(m × n)) time.

Example 1
Input: matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]], target = 3
Output: true
Example 2
Input: matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]], target = 13
Output: false
Solution

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, everything before it is smaller too, and that half can be dropped. If it is bigger, the second half goes. Each look halves what is left, and this halving search on a sorted list is known as binary search.

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 3 by 4 matrix read row by row is one sorted list of 12 values, positions 0 to 11. Position 6 holds 16, which sits in row 6 / 4 = 1, column 6 % 4 = 2.

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 / for division and % for the remainder. In the matrix, row 1, column 2 is indeed 16.

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 target? At the start, all of them. Two markers keep track of the range still in play: lo starts at position 0 and hi at the last position, m × n - 1. Both ends count as part of the range, so the search goes on while lo <= hi.

From a position to a cell

How does a position become a cell? In Java, dividing two int values drops the remainder, and % gives the remainder. With cols columns, position mid is in row mid / cols and column mid % cols, the same arithmetic the picture shows for position 6.

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. Writing it this way, not as (lo + hi) / 2, keeps the sum from passing the largest int on a very large matrix. If the value there equals target, the answer is true. If it is smaller, lo moves to mid + 1; if bigger, hi moves to mid - 1.

Follow Example 2, with target 13. The first mid is 5, which holds 11, too small, so lo becomes 6. Then mid is 8, which holds 23, too big, so hi becomes 7. Then mid is 6, which holds 16, too big again, so hi becomes 5. Now lo is past hi, no positions are left, and the answer is false.

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. Then a second binary search runs inside that row. The cost is O(log m + log n), which is the same as O(log(m × n)).

Java Solution

The method searchMatrix works in these steps:

  1. First, read the size of the matrix: rows is matrix.length and cols is matrix[0].length, the length of the first row.
  2. Set lo to 0 and hi to rows * cols - 1, the first and last positions of the list.
  3. A while loop runs as long as lo <= hi. Each pass picks the middle position mid and reads its value from matrix[mid / cols][mid % cols].
  4. If value equals target, return true. If it is smaller, move lo to mid + 1; otherwise move hi to mid - 1.
  5. If the loop ends because no positions are left, return false.

The main method searches the example matrix for both example targets, for the first and last values, and for a number below and above all of them, then tries a single row, a single column and a single cell.

Java
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:

Output
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: true. The value 60 sits at position 11, the last one. The search reads positions 5, 8 and 10 first, and its final look comes when lo and hi are both 11. The loop still runs then because its check is lo <= hi, not lo < hi. For 0 and 61 the range shrinks off the left or right end, and both lines print false.

The single column line uses a matrix with cols equal to 1. There, position k is row k, column 0, so the search becomes a plain binary search down the column. 5 falls between 4 and 6, and the answer is false.

The divisor in mid / cols matters. With rows, which is 3, in its place, the search for 60 reads position 10 as row 3. The matrix has only rows 0 to 2, so Java throws ArrayIndexOutOfBoundsException: 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, mid and 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 Search a 2D Matrix II.