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.
- Create an empty min heap using heapq in python.
- Now assign first row (list) in result variable and convert result list into min heap using heapify method.
- Now traverse remaining row elements and push them into created min heap.
- Now get k’th smallest element using nsmallest(k, iterable) method of heapq module.
7th smallest element is 30
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.