Suppose we have a 2D matrix, where each row and column is sorted in non-decreasing order, we have to check whether given target is present inside it or not.
So, if the input is like
2 | 4 | 30 |
3 | 4 | 31 |
6 | 6 | 32 |
And target = 31, then the output will be True
To solve this, we will follow these steps −
- col := column size of matrix - 1
- for i in range 0 to row size of matrix, do
- while matrix[i, col] > target and col >= 0, do
- col := col - 1
- if matrix[i, col] is same as target, then
- return True
- while matrix[i, col] > target and col >= 0, do
- return False
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, matrix, target): col = len(matrix[0]) - 1 for i in range(len(matrix)): while matrix[i][col] > target and col >= 0: col = col - 1 if matrix[i][col] == target: return True return False ob = Solution() matrix = [ [2, 4, 30], [3, 4, 31], [6, 6, 32] ] target = 31 print(ob.solve(matrix, target))
Input
matrix = [ [2, 4, 30], [3, 4, 31], [6, 6, 32]] target = 31
Output
True