Menu
CoddyTech

Search a 2D Matrix

MediumBinary searchpython iconjava iconcpp iconc iconjs icon+10

You get a grid of integers matrix with m rows and n columns, and an integer target. Every row is sorted in increasing order, and the first value of each row is greater than the last value of the row above it. Return true if target appears in the grid and false otherwise, in O(log(m × n)) time.

Function

searchMatrix(matrix: integer-2d-array, target: integer) → boolean
matrixinteger-2d-array
the grid, given as a list of rows, sorted row by row
targetinteger
the value to look for
Returnsboolean
true if target is in the grid, false otherwise

Constraints

  • 1 ≤ m, n ≤ 100, where m = matrix.length and n = matrix[i].length
  • Every row has the same length n.
  • -104 ≤ matrix[i][j], target ≤ 104
  • Each row is sorted in strictly increasing order, and the first value of each row is greater than the last value of the previous row.

Examples

Input
matrix = [[2, 5, 9, 14], [17, 21, 26, 30], [33, 38, 45, 52]]target = 26
Output
true
Explanation
Read row by row, the 12 values are one sorted list. A binary search over positions 0 to 11 checks 21 at position 5 (too small), 33 at position 8 (too big), then finds 26 at position 6.
challenge icon

Follow-up

Suppose the rows could have different lengths, still sorted end to end. How would you turn a position into a row and a column, and what would the search cost?

Reset code
def searchMatrix(matrix, target):
    # Write code here

Test #1

Test #2

Arguments

matrix = [[2, 5, 9, 14], [17, 21, 26, 30], [33, 38, 45, 52]]
target = 26

Expected Output

true