CodeSpeek

Search a 2D Matrix

Medium · Binary Search

You are given a matrix of integers where each row is sorted from left to right, and the first number of each row is larger than the last number of the previous row. Given a target value, determine whether it exists anywhere in the matrix. Return true if it does, false otherwise.

Examples

Input:  matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
Why:    3 appears in the first row of the matrix.
Input:  matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false
Why:    13 does not appear in any row of the matrix.
Input:  matrix = [[1]], target = 1
Output: true
Why:    The single element equals the target.

Constraints

1 <= matrix.length <= 100, 1 <= matrix[0].length <= 100, -10^4 <= matrix[i][j], target <= 10^4, each row is sorted ascending and the first element of a row exceeds the last element of the previous row

Practise it by voice

Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.

Practise Search a 2D Matrix

This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Search a 2D Matrix. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.