Leetcode: Kth largest element
1 min readDec 24, 2016
We need to find the kth largest element in an unsorted array.
There are multiple ways to solve this problem
- Sort input in descending order, return kth element, O(n*log(n))
- Selection sort input till kth position, return kth element, O(n*k)
- Convert input to max heap, pop it k times, O(n+klog(n))
- Convert input to min heap, pop it n-k+1 times O(n+(n-k)log(n))
An important point to note in this problem is to use heap every time you need to
- Pick kth smallest/largest element from a list
- Maintain kth smallest/largest element of a dynamic list
As a corollary to above statements heaps should always be used to maintain min or max value of a dynamic array or streaming numbers
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
""" heapq.heapify(nums)
for i in range(len(nums) - k):
heapq.heappop(nums)
return heapq.heappop(nums)
Related Questions
- Given co-ordinates of n points on a 2-d plane find the k closest points to the origin
- Given a streaming list of integers find the median (Hint: use 2 heaps)