Python heapq to find K’th smallest element in a 2D array

Given an n x n matrix and integer k. Find the k’th smallest element in the given 2D array.


Input : mat = [[10, 25, 20, 40],
               [15, 45, 35, 30],
               [24, 29, 37, 48],
               [32, 33, 39, 50]]
        k =  7 
Output : 7th smallest element is 30

We will use similar approach like K’th Smallest/Largest Element in Unsorted Array to solve this problem.

  1. Create an empty min heap using heapq in python.
  2. Now assign first row (list) in result variable and convert result list into min heap using heapify method.
  3. Now traverse remaining row elements and push them into created min heap.
  4. Now get k’th smallest element using nsmallest(k, iterable) method of heapq module.




# Function to find K'th smallest element in 
# a 2D array in Python
import heapq
def kthSmallest(input):
    # assign first row to result variable
    # and convert it into min heap
    result = input[0
    # now traverse remaining rows and push
    # elements in min heap
    for row in input[1:]:
         for ele in row:
    # get list of first k smallest element because
    # nsmallest(k,list) method returns first k 
    # smallest element now print last element of 
    # that list
    kSmallest = heapq.nsmallest(k,result)
    print (k,"th smallest element is ",kSmallest[-1])
# Driver program
if __name__ == "__main__":
    input = [[10, 25, 20, 40],
           [15, 45, 35, 30],
           [24, 29, 37, 48],
           [32, 33, 39, 50]]
    k = 7



7th smallest element is 30

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.