← Whiteboard questions

Search a 2D Matrix

Find a number in a sorted grid where each row continues the row before it

DSA, Medium, Binary Search

Which structure or algorithm, and what does it cost.

A grid matrix has rows of equal length. Each row is sorted from smallest to largest. The first number of each row is larger than the last number of the row before it. You also get a number target. Return True if target appears anywhere in the grid, otherwise return False.

Examples

Input matrix = [[2, 5, 9], [12, 14, 20], [23, 27, 31]], target = 27
Output True
Why 27 is in the last row, second column.
Input matrix = [[2, 5, 9], [12, 14, 20], [23, 27, 31]], target = 10
Output False
Why 10 falls between 9 and 12, so it is in no row.
Input matrix = [[3, 8, 12, 40]], target = 40
Output True
Why Edge case: only one row, and the target is its last cell. Nothing special should be needed for a single row.

Constraints

Your answer must contain

Target Aim for O(log(rows * columns)) time and O(1) memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Look at the last number of one row and the first number of the next row. What does the order look like across that boundary?

Hint 2 the approach

This is one sorted list in disguise. You can search it as a list without building a copy of it.

Hint 3 the key step

Search positions 0 to rows times columns minus 1. How do you turn one position back into a row and a column, using only the column count?

Walkthrough

Full walkthrough brute force to best

Brute force

Check every cell. That is O(rows * columns) time and O(1) memory, up to 90,000 checks for a 300 by 300 grid. It ignores the sorted order.

Better method

Binary search the first column to find the last row whose first value is at most the target. Then binary search inside that row. This costs O(log rows + log columns) time, the same order as the best method, but it needs two loops and two sets of edge cases.

Best method

Each row starts above the end of the row before it, so reading the grid row by row gives one sorted list of rows * columns values. Run binary search on the positions 0 to rows * columns - 1 and never build the list. Position p lives at row p // columns and column p % columns. Compare that value with the target and keep the left or the right part, as in a plain binary search. There is one loop and one range, so there are fewer places to slip.

Hand trace

Run on the 3 by 3 grid with target 27. There are 9 positions, so lo is 0 and hi is 8. The middle position 4 is row 1, column 1, value 14. 14 is smaller than 27, so lo becomes 5. The middle position 6 is row 2, column 0, value 23. It is smaller again, so lo becomes 7. The middle position 7 is row 2, column 1, value 27. It matches, so return True.

Code

def search_matrix(matrix, target):
    rows, cols = len(matrix), len(matrix[0])
    lo, hi = 0, rows * cols - 1     # positions in the grid read row by row
    while lo <= hi:
        mid = (lo + hi) // 2
        value = matrix[mid // cols][mid % cols]
        if value == target:
            return True
        if value < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return False

Time and memory

O(log(rows * columns)) time, because the range of positions halves each step: at most 17 steps for 90,000 cells. O(1) memory, since the flat list is never built.

Common mistakes

  • Swapping rows and columns in the position formula. The row is p // columns and the column is p % columns.
  • Building the flat list first. That costs O(rows * columns) time and memory and throws away the benefit of searching.
  • Ignoring the rule that each row starts above the end of the row before it. Without it the grid is not one sorted list, and this method can give wrong answers.

Related problems

More Binary Search problems
Search a 2D Matrix: hints, walkthrough and Python solution