Program to find smallest intersecting element of each row in a matrix in Python


Suppose we have a 2D matrix where each row is sorted in ascending order. We have to find the smallest number that exists in every row. If there's no such result, then return −1.

So, if the input is like

235
51010
135

then the output will be 5

To solve this, we will follow these steps −

  • if matrix is empty, then

    • return −1

  • first := a new set from first row of matrix

  • for each row in matrix, do

    • first := Intersect first a set of elements of row

    • if first is empty, then

      • return −1

  • return minimum of first

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, matrix):
      if not matrix:
         return -1
      first = set(matrix[0])
      for row in matrix:
         first &= set(row)
         if not first:
            return -1
      return min(first)
ob1 = Solution()
matrix = [
   [2, 3, 5],
   [5, 10, 10],
   [1, 3, 5]
]
print(ob1.solve(matrix))

Input

matrix = [
[2, 3, 5],
[5, 10, 10],
[1, 3, 5] ]

Output

5

Updated on: 21-Oct-2020

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements