Program to find a target value inside given matrix or not in Python


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

2430
3431
6632

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
  • return False

Let us see the following implementation to get better understanding −

Example

 Live Demo

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

Updated on: 20-Nov-2020

280 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements