
Finding the Kth Smallest Element in an Array Using Heap (Min Heap) in Python
Problem Explanation Given an integer array arr[] and an integer k , the task is to find the kth smallest element in the array. The kth smallest element is determined based on the sorted order of the array. Example: Input: arr = [10, 5, 4, 3, 48, 6, 2, 33, 53, 10], k = 4 Output: 5 Input: arr = [7, 10, 4, 3, 20, 15], k = 3 Output: 7 Method Used: Min Heap A Min Heap is a data structure where the smallest element is always at the root. Steps: Convert the array into a min heap Remove the smallest element k-1 times The next removed element will be the kth smallest Why This Method? More efficient than repeated minimum search Time complexity: O(n + k log n) Does not require full sorting Useful for large datasets Python Code import heapq class Solution : def kthSmallest ( self , arr , k ): heapq . heapify ( arr ) # Convert list into a min heap for i in range ( k - 1 ): # Remove smallest k-1 elements heapq . heappop ( arr ) return heapq . heappop ( arr ) # Return kth smallest element Code Explan
Continue reading on Dev.to Python
Opens in a new tab


