- 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 nth smallest number from a given matrix in Python
Suppose we have a 2D matrix, where each row and column is sorted in non-decreasing order, we have to find the nth smallest number.
So, if the input is like
2 | 4 | 30 |
3 | 4 | 31 |
6 | 6 | 32 |
And n = 4, then the output will be 6.
To solve this, we will follow these steps −
- lst := a new list
- for each row i in matrix, do
- for each cell j in i, do
- insert j at the end of lst
- for each cell j in i, do
- sort the list lst
- return lst[n]
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, matrix, n): lst = [] for i in matrix: for j in i: lst.append(j) lst.sort() return lst[n] ob = Solution() matrix = [ [2, 4, 30], [3, 4, 31], [6, 6, 32] ] n = 4 print(ob.solve(matrix, n))
Input
matrix = [ [2, 4, 30], [3, 4, 31], [6, 6, 32] ] n = 4
Output
6
Advertisements