- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Find maximum element of each row in a matrix in C++
- Python program to find the redundancy rates for each row of a matrix
- Kth Smallest Element in a Sorted Matrix in Python
- C++ program to find the Sum of each Row and each Column of a Matrix
- Program to find nth smallest number from a given matrix in Python
- Program to find kth smallest element in linear time in Python
- Python Program to find the Next Nearest element in a Matrix
- Program to replace each element by smallest term at left side in Python
- Program to find number of elements in matrix follows row column criteria in Python
- Python program to find k'th smallest element in a 2D array
- Program to find the kth smallest element in a Binary Search Tree in Python
- Program to find valid matrix given row and column sums in Python
- How to find the row products for each row in an R matrix?
- Find maximum element of each column in a matrix in C++
- Python Program to convert a list into matrix with size of each row increasing by a number

Advertisements