MEDIUM NC#64 Heap / Priority Queue
703. Kth Largest Element in a Stream
๐ Problem
Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element. Implement KthLargest class: - KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums. - int add(int val) Appends the integer val to the stream and returns the element representing the kth largest element in the stream.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขLevel-order traversal
- โขQueue discipline
- โขShortest-step interpretation
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply BFS reasoning pattern
- โขApply Heap reasoning pattern
๐ก Approach
- โ Use min heap of size k
- โ Heap always contains k largest elements seen so far
- โ Top of heap is kth largest element
- โ When adding new element, push and maintain heap size
- โ Time: O(n log k) for initialization, O(log k) for add, Space: O(k)
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse min heap of size k
- โขHeap always contains k largest elements seen so far
- โขTop of heap is kth largest element
Common Pitfalls
- โขWhen adding new element, push and maintain heap size
- โขTime: O(n log k) for initialization, O(log k) for add, Space: O(k)
๐งช Test Cases
Hidden tests on submit: 2
Test Case 1
Not run Input:
(() => { const kthLargest = new KthLargest(3, [4,5,8,2]); return kthLargest.add(3); })(); Expected:
4 Test Case 2
Not run Input:
(() => { const kthLargest = new KthLargest(3, [4,5,8,2]); kthLargest.add(3); return kthLargest.add(5); })(); Expected:
5 Test Case 3
Not run Input:
(() => { const kthLargest = new KthLargest(3, [4,5,8,2]); kthLargest.add(3); kthLargest.add(5); return kthLargest.add(10); })(); Expected:
5 ๐ Code Editor
๐ค Output