Search for a target value in a matrix with sorted rows and row-to-row ordering.
Problem
You are given a 2D matrix of integers with m rows and n columns.
The matrix has the following 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 a target value, determine whether it exists in the matrix.
Return true if the target is present, otherwise return false.
Intuition
Because the rows are ordered globally, the entire matrix can be treated like a single sorted array for searching.
Input Format
- The first line contains two integers
mandn. - The next
mlines each containnintegers describing the matrix. - The final line contains the integer
target.
Output Format
- Print
trueiftargetexists in the matrix. - Otherwise print
false.
Constraints
1 <= m, n- The matrix is row-wise sorted in non-decreasing order.
- The first element of each row is strictly greater than the last element of the previous row.
- Integers may be negative or positive.
Example 1
Input
3 4 1 3 5 7 10 11 16 20 23 30 34 60 3
Output
true
Explanation
The target 3 appears in the first row.
Example 2
Input
3 4 1 3 5 7 10 11 16 20 23 30 34 60 13
Output
false
Explanation
The target 13 does not appear anywhere in the matrix.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.