- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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

- if nums[i] > maxHeap[0], then
- 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

- Related Questions & Answers
- Program to find kth smallest n length lexicographically smallest string in python
- Program to find the kth smallest element in a Binary Search Tree in Python
- Kth Smallest Element in a BST in Python
- Python Program to Select the nth Smallest Element from a List in Expected Linear Time
- Kth Smallest Element in a Sorted Matrix in Python
- C++ Program to find kth Smallest Element by the Method of Partitioning the Array
- Kth smallest element after every insertion in C++
- Python – Find Kth Even Element
- C++ Program to Find kth Largest Element in a Sequence
- Python Program to Select the nth Largest Element from a List in Expected Linear Time
- Find smallest element greater than K in Python
- Python program to find k'th smallest element in a 2D array
- Program to find smallest intersecting element of each row in a matrix in Python
- Program to schedule tasks to take smallest amount of time in Python
- C# Program to find the smallest element from an array

Advertisements