
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- Related Articles
- Program to find number of distinct island shapes from a given matrix in Python
- Program to find Nth Fibonacci Number in Python
- C++ Program to find the smallest digit in a given number
- Python Program to Select the nth Smallest Element from a List in Expected Linear Time
- Python program to find the smallest number in a list
- Program to reduce list by given operation and find smallest remaining number in Python
- Program to find smallest intersecting element of each row in a matrix in Python
- Program to count number of islands in a given matrix in Python
- Program to find smallest string with a given numeric value in Python
- Program to find maximum amount of coin we can collect from a given matrix in Python
- Program to find the transpose of given matrix in Python
- Nth Catalan Number in Python Program
- Program to find nth ugly number in C++
- C++ Program to find out if a palindromic matrix can be made from a given matrix
- 8085 program to find nth power of a number

Advertisements