Leetcode 215 : Kth Largest Element in the Array (solution in python )

Deepa Saw
1 min readApr 7, 2024

--

class Solution(object):
def findKthLargest(self, nums, k):
heap = []
for num in nums:
heapq.heappush(heap, num)
if len(heap) > k:
heapq.heappop(heap)

return heap[0]

This code implements a method `findKthLargest` to find the kth largest element in a list of numbers `nums` using a min-heap. Here’s an explanation:

1. It initializes an empty heap.
2. It iterates through each number in `nums`, pushing it into the heap.
3. If the size of the heap exceeds k, it pops the smallest element (keeping the heap size at k).
4. After iterating through all elements, the top element of the heap is the kth largest.

Time Complexity: Inserting elements into the heap and popping the smallest element each time takes O(n log k) time, where n is the number of elements in `nums`.
Space Complexity: The space used by the heap is O(k), as it stores at most k elements.

Overall, this approach efficiently finds the kth largest element using a min-heap with a space-efficient implementation.

--

--