MediumArrayBinary SearchMatrix

Search a 2D Matrix II

1 approach, code in every language

Problem description

You are given a matrix in which every row is sorted in ascending order from left to right and every column is sorted in ascending order from top to bottom. Given a target value, decide whether it exists somewhere in the matrix.

Unlike a fully sorted grid, the rows and columns are only individually sorted, so a plain binary search over a flattened view will not work. You need a strategy that exploits both orderings at once.

Example 1

Input: matrix = [[1, 4, 7], [2, 5, 8], [3, 6, 9]], target = 5

Output: true

Following the ordering from the top-right corner leads to the cell holding 5, so the target is present.

Example 2

Input: matrix = [[1, 4, 7], [2, 5, 8], [3, 6, 9]], target = 10

Output: false

The largest value in the matrix is 9, so 10 cannot be found anywhere.

Constraints

  • 1 <= m, n <= 300
  • -10^9 <= matrix[i][j] <= 10^9
  • Each row is sorted in ascending order
  • Each column is sorted in ascending order

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free