
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
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 Articles
- Program to find the kth smallest element in a Binary Search Tree in Python
- Program to find kth smallest n length lexicographically smallest string in python
- Python Program to Select the nth Smallest Element from a List in Expected Linear Time
- Kth Smallest Element in a BST in Python
- Kth Smallest Element in a Sorted Matrix in Python
- Kth smallest element after every insertion in C++
- C++ Program to find kth Smallest Element by the Method of Partitioning the Array\n
- 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
- 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
- Find smallest element greater than K in Python
- Program to schedule tasks to take smallest amount of time in Python
- Kth Largest Element in an Array in Python

Advertisements