Search a 2D Matrix

Medium#74find a number

You get a matrix where each row is sorted and each row starts with a number bigger than the last number of the row above. Say whether a target number is in it, in O(log(rows · cols)) time. Our example: the 3 × 4 matrix with rows [2, 4, 7, 9], [12, 15, 18, 20], [23, 26, 30, 34] and 26 — the answer is true.

input
matrix: m rows of n integers, each row in non-decreasing order, and the first number of each row greater than the last of the row above; target: an integer.
returns
true if target is in matrix, false if not. LeetCode wants it in O(log(m · n)).
constraints
  • 1 ≤ m = matrix.length ≤ 100
  • 1 ≤ n = matrix[i].length ≤ 100, the same for every row
  • −10⁴ ≤ matrix[i][j] ≤ 10⁴
  • each row is in non-decreasing order; the first number of a row is greater than the last of the row above
  • −10⁴ ≤ target ≤ 10⁴
our 16 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[][]} matrix
 * @param {number} target
 * @return {boolean}
 */
function searchMatrix(matrix, target) {

}
Ctrl ↵
format
reset

saved in this browser

16 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more binary search problems

Pattern “Binary search” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.