- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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
Advertisements