Program to find nth smallest number from a given matrix in Python

PythonServer Side ProgrammingProgramming

Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

Practical Data Science using Python

22 Lectures 6 hours

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
• sort the list lst
• return lst[n]

Let us see the following implementation to get better understanding −

Example

Live Demo

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
Updated on 20-Nov-2020 05:47:00