![]() |
VOOZH | about |
Given a matrix mat[][] and an integer x, the task is to check if x is present in mat[][] or not. Every row and column of the matrix is sorted in increasing order.
Examples:
Input: x = 62, mat[][] = [[3, 30, 38],
[20, 52, 54],
[35, 60, 69]]
Output: false
Explanation: 62 is not present in the matrix.Input: x = 55, mat[][] = [[18, 21, 27],
[38, 55, 67]]
Output: true
Explanation: mat[1][1] is equal to 55.Input: x = 35, mat[][] = [[3, 30, 38],
[20, 52, 54],
[35, 60, 69]]
Output: true
Explanation: mat[2][0] is equal to 35.
Table of Content
The simple idea is to traverse the complete matrix and search for the target element. If the target element is found, return true. Otherwise, return false.
true
To optimize the above approach we are going to use the Binary Search algorithm.
The problem specifies that each row in the given matrix is sorted in ascending order. Instead of searching each column sequentially, we can efficiently apply Binary Search on each row to determine if the target is present.
true
The idea is to remove a row or column in each comparison until an element is found. Start searching from the top-right corner of the matrix. There are 3 possible cases:
- x is greater than the current element: This ensures that all the elements in the current row are smaller than the given number as the pointer is already at the right-most element and the row is sorted. Thus, the entire row gets eliminated and continues the search from the next row.
- x is smaller than the current element: This ensures that all the elements in the current column are greater than the given number. Thus, the entire column gets eliminated and continues the search from the previous column, i.e. the column on the immediate left.
- The given number is equal to the current number: This will end the search.
Illustration:
true
Related Article: Search element in a sorted matrix