AlgoLounge

Search a 2D Matrix

medium

Leetcode 74. Search a 2D Matrix

You are given an m x n 2D integer matrix with the following two properties:

  • Each row is sorted in non-decreasing order.
  • The first integer of each row is greater than the last integer of the previous row.

Given an integer target, return True if target is in the matrix, or False otherwise.

You must write a solution in O(log(m * n)) time complexity.

Examples

Example 1

Input:  matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: True

Example 2

Input:  matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: False

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 100
  • -10^4 <= matrix[i][j], target <= 10^4
TypeScript
Loading editor…
List of test cases (8)
Case 1
matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]]
target = 3
Case 2
matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]]
target = 13
Case 3
matrix = [[1]]
target = 1
Case 4
matrix = [[1]]
target = 2
Case 5
matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]]
target = 60
Case 6
matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]]
target = 1
Case 7
matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]]
target = 0
Case 8
matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]]
target = 100