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

Search a 2D Matrix

MediumBinary search

You get a grid of whole numbers, matrix, with m rows and n columns. Every row is sorted from small to large, and each row starts with a number bigger than the last number of the row above it. So reading the grid row by row, left to right, gives one sorted list.

Return true if target appears anywhere in the grid, and false if it does not. Aim for O(log(m · n)) time.

Example 1

Input:  matrix = [[2, 4, 8, 9], [12, 15, 19, 21], [30, 33, 38, 47]], target = 19
Output: true
Why:    19 is in the middle row
2 more examples and the constraints

Example 2

Input:  matrix = [[2, 4, 8, 9], [12, 15, 19, 21], [30, 33, 38, 47]], target = 10
Output: false
Why:    10 falls between 9 and 12

Example 3

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

Constraints

  • 1 ≤ m, n ≤ 100
  • −10,000 ≤ every value and target ≤ 10,000
  • Rows are sorted, and each row starts above where the previous one ended

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. Staircase from the cornerO(m + n)
  3. One binary searchO(log(m · n))

The idea in one sentence

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

Side by side

ApproachTimeRelative work for a 100 × 100 gridVerdict
Check every cellO(m · n)
Correct; ignores the order
Staircase from the cornerO(m + n)
Passes; misses the log bound
One binary searchO(log(m · n))
Best; what the task asks for

m = rows, n = columns.

Edge cases to test

  • One cell. [[7]] gives lo = hi = 0; the loop must still read it once.
  • Target in a gap. 10 sits between the end of one row and the start of the next; the search must end with false.
  • Outside the range. A target below the first cell or above the last one.
  • One row or one column. With n = 1 every index is its own row; the formula still works.

Common mistakes

  • Turning the index into a cell with m instead of n: row = mid // m reads the wrong cell.
  • Writing while lo < hi, which skips the last remaining cell.
  • Binary searching for the row first and then forgetting the target can fall in a gap between rows.

How to talk through it

  1. 1Clarify. Is each row strictly after the previous one? Can the grid be a single row or a single cell?
  2. 2Give the scan. Check every cell; say it is O(m · n) and ignores the sorting.
  3. 3Spot the hidden list. Read row by row, the grid is one sorted list of m · n numbers.
  4. 4Code the binary search. Search indexes 0 to m · n − 1 and map each to row mid // n, column mid % n.
  5. 5Test out loud. Run the one-cell grid and a target that falls between two rows.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?