
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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
Advertisements