Program to find kth smallest element in linear time in Python


Suppose we have a list of numbers called nums, we also have another value k, we have to find the kth (starting from 0) smallest element in the list. We have to solve this problem in O(n) time on average.

So, if the input is like nums = [6, 4, 9, 3, 1] k = 2, then the output will be 4, as after sorting the list will be like [1, 3, 4, 6, 9], the kth smallest element is 4.

To solve this, we will follow these steps −

  • maxHeap := a new empty heap
  • for i in range 0 to k, do
    • insert nums[i] into maxHeap
  • for i in range k + 1 to size of nums - 1, do
    • if nums[i] > maxHeap[0], then
      • delete top from maxHeap
      • insert nums[i] into maxHeap
  • return maxHeap[0]

Example

Let us see the following implementation to get better understanding −

from heapq import heappop, heappush
def solve(nums, k):
   maxHeap = []
   for i in range(k + 1):
      heappush(maxHeap, -nums[i])
   for i in range(k + 1, len(nums)):
      if nums[i] < -maxHeap[0]:
         heappop(maxHeap)
         heappush(maxHeap, -nums[i])
   return -maxHeap[0]

nums = [6, 4, 9, 3, 1]
k = 2
print(solve(nums, k))

Input

[6, 4, 9, 3, 1], 2

Output

4

Updated on: 19-Oct-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements