#703
Kth Largest Element in a Stream
EasyTreeDesignBinary Search TreeHeap (Priority Queue)Binary TreeData StreamHeap (Min-Heap for this problem)Sorting (Brute-force approach)
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n log n) | O(log k) |
| Space | O(n) | O(k) |
💡
Intuition
Time O(log k)Space O(k)
Using a min-heap allows us to efficiently keep track of the kth largest element without needing to sort the entire list every time. We maintain a heap of size k, which gives us O(log k) time complexity for adding new scores.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a min-heap of size k with the first k elements from the stream.
- 2Step 2: For each new score, if the score is larger than the smallest in the heap, replace the smallest.
- 3Step 3: The root of the min-heap will always be the kth largest element.
solution.py16 lines
1import heapq
2
3class KthLargest:
4 def __init__(self, k: int, nums: List[int]):
5 self.k = k
6 self.min_heap = nums[:k]
7 heapq.heapify(self.min_heap)
8 for num in nums[k:]:
9 self.add(num)
10
11 def add(self, val: int) -> int:
12 if len(self.min_heap) < self.k:
13 heapq.heappush(self.min_heap, val)
14 elif val > self.min_heap[0]:
15 heapq.heappushpop(self.min_heap, val)
16 return self.min_heap[0]ℹ
Complexity note: Maintaining a min-heap of size k takes O(log k) time for each addition and O(k) space for the heap.
- 1Using a min-heap allows for efficient tracking of the kth largest element as new scores are added.
- 2Maintaining a fixed-size heap ensures that we only keep the necessary elements for our kth largest calculation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.