oneby7

Binary Search Searching a matrix

253. Search a 2D Matrix

Medium

You are given a matrix of integers matrix with m rows and n columns, and an integer target. The matrix is sorted in two ways:

  • Each row is sorted from left to right in non-decreasing order.
  • The first value of each row is larger than the last value of the row above it.

Return true if target is in the matrix, and false if it is not. Aim for a running time of O(log(m · n)).

Example 1

-7-214912121521303340

Input: matrix = [[-7, -2, 1, 4], [9, 12, 12, 15], [21, 30, 33, 40]] target = 12

Output: true

Explanation: 12 is in row 1, twice, at columns 1 and 2. A value can repeat within a row.

Example 2

358111420

Input: matrix = [[3, 5, 8], [11, 14, 20]], target = 10

Output: false

Explanation: 10 is larger than 8, the last value of row 0, and smaller than 11, the first value of row 1. So it is in neither row.

Example 3

−10⁹-3010⁹

Input: matrix = [[-1000000000], [-3], [0], [1000000000]] target = 1000000000

Output: true

Explanation: The matrix is a single column, and the target is the largest allowed value, in the last cell.

Check your understanding

Work out the answer for this input before you write any code.

matrix = [[1, 4, 7], [10, 13, 16]], target = 8

Constraints

  • m == matrix.length, n == matrix[i].length
  • 1 ≤ m, n ≤ 105
  • 1 ≤ m · n ≤ 105
  • -109 ≤ matrix[i][j] ≤ 109
  • -109 ≤ target ≤ 109
  • Each row is sorted in non-decreasing order.
  • matrix[i][0] > matrix[i - 1][n - 1] for every row i ≥ 1

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.