Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Search in a 2D Matrix

Medium Acceptance 86.00% Points 30.00

You are given an m × n integer matrix matrix with the following properties:

Each row is sorted in ascending order.

The first element of each row is greater than the last element of the previous row.

Given an integer target, return true if the target exists in the matrix, otherwise return false.

Examples
Example 1

Example 1

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

Output: true

Explanation: The element 3 exists in the first row of the matrix, so the result is true.

Example 2

Example 2

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

Output: false

Explanation: The element 13 does not exist in any row of the matrix, so the result is false.

Example 3

Example 3

Input: matrix = [[2,4,6],[8,10,12],[14,16,18]], target = 16

Output: true

Explanation: The element 16 exists in the last row of the matrix, so the result is true.

Hints
Hint 1
N/A
Constraints
  • 1 = m, n = 100
  • -104 = matrix[i][j], target = 104
Companies
Samsung
Topics
Recursion Binary Search
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions