oneby7

Binary Search Searching a matrix

254. Search a 2D Matrix II

Medium

You are given a grid of integers matrix with m rows and n columns, and an integer target. Every row is sorted from left to right, and every column is sorted from top to bottom, smallest value first. A value can appear more than once.

Return true if some cell of matrix holds target, and false otherwise.

A row does not have to start where the row above it ended. In Example 1, the first row ends with 14 and the second row starts with 4.

Example 1

25914471220811152310161930

Input: matrix = [[2, 5, 9, 14], [4, 7, 12, 20], [8, 11, 15, 23], [10, 16, 19, 30]] target = 15

Output: true

Explanation: The cell in row 2 and column 2 holds 15, counting rows and columns from 0.

Example 2

-9-403-5-26712811

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

Output: false

Explanation: -3 lies between the smallest value, -9, and the largest, 11, but no cell holds it.

Example 3

1336

Input: matrix = [[1], [3], [3], [6]], target = 6

Output: true

Explanation: The matrix can be a single column. Its last cell holds 6.

Check your understanding

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

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

Constraints

  • m == matrix.length, n == matrix[i].length
  • 1 ≤ m, n ≤ 105
  • 1 ≤ m · n ≤ 105
  • -109 ≤ matrix[i][j] ≤ 109
  • -109 ≤ target ≤ 109
  • Every row is sorted in non-decreasing order from left to right, and every column from top to bottom.

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.