Problem
Design a class that is constructed with an integer k and an initial integer stream, and that supports adding a new value and returning the current kth largest element after each add.
Examples
Example 1
`KthLargest: KthLargest(3, [4, 5, 8, 2]), add(3), add(5), add(10), add(9), add(4)``[null, 4, 5, 5, 8, 8]`Constraints
0 <= nums.length <= 10^41 <= k <= nums.length + 1-10^4 <= nums[i] <= 10^4-10^4 <= val <= 10^4- At most
10^4calls will be made toadd.
Hints
Hint 1
The constructor can be given fewer than k numbers. After enough additions, every
addreturns the kth largest among all values seen so far, including the initial ones.Hint 2
This is the streaming form of "kth largest": a size-k min-heap.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Store every number, sort on each add, and pick index k from the end.
Optimal. A min-heap of at most k elements. The root is the answer after each insertion.
Alternative. A balanced tree of all values also works, but it uses more memory than a heap of size k.
Complexity
- Time
- O(n log k)
Constructor is O(n log k). Each add is O(log k). The heap uses O(k) space.
- Space
- O(k)
Code
import heapq
class KthLargest:
def __init__(self, k: int, nums: list[int]) -> None:
self.k = k
self.heap = []
for x in nums:
self.add(x)
def add(self, val: int) -> int:
heapq.heappush(self.heap, val)
if len(self.heap) > self.k:
heapq.heappop(self.heap)
return self.heap[0]
if __name__ == "__main__":
s = KthLargest(3, [4, 5, 8, 2])
assert s.add(3) == 4
assert s.add(5) == 5
assert s.add(10) == 5
assert s.add(9) == 8
assert s.add(4) == 8
print("ok")import java.util.PriorityQueue;
public class KthLargestElementInAStream {
private final int k;
private final PriorityQueue<Integer> heap = new PriorityQueue<>();
KthLargestElementInAStream(int k, int[] nums) {
this.k = k;
for (int x : nums) add(x);
}
int add(int val) {
heap.offer(val);
if (heap.size() > k) heap.poll();
return heap.peek();
}
public static void main(String[] args) {
var s = new KthLargestElementInAStream(3, new int[] {4, 5, 8, 2});
if (s.add(3) != 4) throw new AssertionError();
if (s.add(5) != 5) throw new AssertionError();
if (s.add(10) != 5) throw new AssertionError();
if (s.add(9) != 8) throw new AssertionError();
if (s.add(4) != 8) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official sample: constructed with k = 3 and [4,5,8,2], then add 3 returns 4, add 5 returns 5, add 10 returns 5, add 9 returns 8, and add 4 returns 8.
- If fewer than k numbers have been seen, the official tests still call add only after the heap can answer; keep the same size-k rule anyway.
Follow-ups
- Returning a full top-k list after each add is the same heap, then a sort of those k values.
Interview script
"I reuse the kth-largest min-heap idea in a class. The constructor offers every initial value, and add does the same: keep k elements, return the root."
Source: LeetCode 703: Kth Largest Element in a Stream Source: Java SE 17 API: PriorityQueue
Sources (2)
- LeetCode 703: Kth Largest Element in a Streamleetcode.com
- Java SE 17 API: PriorityQueuedocs.oracle.com