DIY: Search a 2D Matrix II

Solve the interview question "Search a 2D Matrix II" in this lesson.

Problem statement

Write an algorithm that searches for a target value in an m x n integer matrix.

The matrix has the following properties:

  • Integers in each row are sorted in ascending order from left to right.

  • Integers in each column are sorted in ascending order from top to bottom.

Input

The input will be an m x n matrix of integers and a target integer value. The following is an example input:

matrix = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[21,22,23,24,25]]

target = 25

Output

The output will be a Boolean value. The following is an example output for the above input:

true

The number 25 is present in the m x n matrix.

Coding exercise

Implement the search_matrix(matrix, target) function, where matrix is the m x n matrix of integers and target is the value that needs to be searched. The function will return a single Boolean value representing whether target exists in matrix or not.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.