# Program to find kth smallest element in linear time in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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, then
• delete top from maxHeap
• insert nums[i] into maxHeap
• return maxHeap

## 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:
heappop(maxHeap)
heappush(maxHeap, -nums[i])
return -maxHeap

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

## Input

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

## Output

4