Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up

Search in a 2D Matrix

Medium Acceptance 86% Points 30

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.

Constraints
  • 1 = m, n = 100
  • -104 = matrix[i][j], target = 104
Topics
Recursion Binary Search
Companies
Samsung
Added 19 Jul 2026 86% acceptance
Ln 1, Col 1Sign in to save your code
1 3 5 7
10 11 16 20
23 30 34 60
3
true