Skip to content
Problem 240 · LeetCode 240(opens in a new tab)

Search a 2D Matrix II

MediumBinary search

You get an m × n integer grid matrix and a number target. Every row is sorted from left to right, and every column is sorted from top to bottom, both in increasing order.

Return true if target appears anywhere in the grid, and false if it does not. Try to do better than reading every cell.

Example 1

Input:  matrix = [[2,5,9,14],[3,7,11,16],[6,10,13,20],[8,12,17,22]], target = 10
Output: true
Why:    10 sits in row 2, column 1
2 more examples and the constraints

Example 2

Input:  the same matrix, target = 15
Output: false
Why:    15 falls between 14 and 16 but is not in the grid

Example 3

Input:  matrix = [[4]], target = 4
Output: true
Why:    the only cell is the target

Constraints

  • 1 ≤ m, n ≤ 300
  • −10⁹ ≤ matrix[i][j], target ≤ 10⁹
  • Each row and each column is in non-decreasing order

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Check every cellO(m · n)
  2. Binary search each rowO(m log n)
  3. Walk from the top-right cornerO(m + n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeCells read for a 300 × 300 missVerdict
Check every cellO(m · n)
Ignores the order
Binary search each rowO(m log n)
Passes; uses rows only
Walk from the top-right cornerO(m + n)
Best; a row or column per step

m = rows, n = columns.

Edge cases to test

  • One cell. [[4]] is true for 4 and false for anything else.
  • One row or one column. The walk turns into a plain scan along that line, still within m + n steps.
  • Target outside the range. Smaller than matrix[0][0] or bigger than the bottom-right cell: the walk falls off quickly and returns false.
  • Repeated values. Equal neighbours do not break the walk: a match is still a match, and every move still drops only impossible cells.

Common mistakes

  • Starting at the top-left corner, where both directions grow and no move is safe.
  • Treating the grid as one sorted list, as in Search a 2D Matrix; row ends here can be bigger than the next row’s start.
  • Checking the bounds after reading matrix[r][c], which reads past the grid.

How to talk through it

  1. 1Clarify. Are both rows and columns sorted? Can values repeat? Is the matrix ever empty?
  2. 2Give the scan. O(m · n) works for any grid; say it ignores the ordering.
  3. 3Improve with rows. A binary search per row gives O(m log n).
  4. 4Use both orders. From the top-right, each comparison drops a row or a column: O(m + n).
  5. 5Test out loud. Run a one-cell grid, a missing target and the two far corners before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?