434. Check if Target Exists in Sorted 2D Matrix

EasyBinary SearchArrayMatrixBinary Search

Given an m×n matrix where each row is sorted left-to-right and the first element of each row is greater than the last element of the previous row, determine if target exists in the matrix. Solve in O(log(m*n)).

Input: A 2D sorted integer matrix and integer target.

Output: true if target exists, false otherwise.

Examples

Example 1
Input: [[1,3,5,7],[9,11,13,15],[17,19,21,23]], 13
Output: true
Explanation: Treat as flat sorted array. index 10 → row=10//4=2, col=10%4=2 → matrix[2][2]=21. Binary search finds 13 at index 6.
Example 2
Input: [[1,3,5,7],[9,11,13,15],[17,19,21,23]], 14
Output: false
Explanation: 14 is not present; binary search returns false.
Example 3
Input: [[1]], 1
Output: true
Explanation: Single element equals target.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →