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

PythonServer Side ProgrammingProgramming

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

2430
3431
6632

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
raja
Published on 20-Nov-2020 05:46:31
Advertisements