- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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

2 | 3 | 5 |

5 | 10 | 10 |

1 | 3 | 5 |

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

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

- Related Questions & Answers
- Find maximum element of each row in a matrix in C++
- Python program to find the redundancy rates for each row of a matrix
- C++ program to find the Sum of each Row and each Column of a Matrix
- Kth Smallest Element in a Sorted Matrix in Python
- Find Intersecting Intervals in Python
- Find maximum element of each column in a matrix in C++
- Program to find nth smallest number from a given matrix in Python
- How to find the row products for each row in an R matrix?
- Program to find kth smallest element in linear time in Python
- Program to replace each element by smallest term at left side in Python
- Python Program to find the cube of each list element
- Python Program to find the Next Nearest element in a Matrix
- Python program to find k'th smallest element in a 2D array
- Python Program to convert a list into matrix with size of each row increasing by a number
- How to add a vector to each row of a matrix in R?

Advertisements