Kth Largest Element in a Stream - Problem

Imagine you're working for a university admissions office during application season. As test scores stream in real-time, you need to continuously track the k-th highest score to determine admission cutoffs dynamically.

Your task is to implement a KthLargest class that efficiently maintains this information:

  • Constructor: KthLargest(int k, int[] nums) - Initialize with the value k and an initial array of scores
  • Add Method: int add(int val) - Add a new score and return the current k-th largest score

The key challenge is that you need to return the k-th largest element after each addition, not just once. This requires an efficient data structure that can handle frequent insertions while quickly retrieving the k-th largest element.

Example: If k=3 and you have scores [4, 5, 8, 2], the 3rd largest is 4. When you add 3, the new 3rd largest becomes 4. When you add 5, it becomes 5.

Input & Output

example_1.py โ€” Basic Operations
$ Input: k = 3, nums = [4, 5, 8, 2] Operations: add(3), add(5), add(10), add(9), add(4)
โ€บ Output: [4, 5, 5, 8, 8]
๐Ÿ’ก Note: Initially, the 3rd largest among [4,5,8,2] is 4. After adding 3: [8,5,4,3,2] โ†’ 3rd largest is 4. After adding 5: [8,5,5,4,3,2] โ†’ 3rd largest is 5. After adding 10: [10,8,5,5,4,3,2] โ†’ 3rd largest is 5. And so on.
example_2.py โ€” Small K Value
$ Input: k = 1, nums = [] Operations: add(-3), add(-2), add(-4), add(0), add(4)
โ€บ Output: [-3, -2, -2, 0, 4]
๐Ÿ’ก Note: When k=1, we're always looking for the maximum element. Starting with empty array, each add returns the largest element seen so far.
example_3.py โ€” Edge Case with Duplicates
$ Input: k = 2, nums = [0] Operations: add(-1), add(1), add(-2), add(-4), add(3)
โ€บ Output: [-1, 0, 0, 0, 1]
๐Ÿ’ก Note: With k=2, we track the 2nd largest element. Starting with [0], adding -1 gives [-1,0] so 2nd largest is -1. Adding 1 gives [-1,0,1] so 2nd largest is 0, and so on.

Visualization

Tap to expand
๐Ÿ† VIP Restaurant AnalogyVIP Section (Capacity: 3)Seat 1$8Seat 2$5Seat 3$4Minimum SpenderNew Customer Arrives: $10Since $10 > $4 (minimum VIP), kick out $4 customerNew VIP list: [$10, $8, $5] โ†’ New minimum: $5๐Ÿ”‘ Key InsightA min-heap of size K keeps the K largest elements,with the K-th largest always at the root!Time: O(log K) | Space: O(K)
Understanding the Visualization
1
Initialize VIP List
Start with customers spending [4, 5, 8, 2]. Your VIP section keeps [8, 5, 4] with 4 as the minimum VIP spender.
2
Customer Spends 3
Customer spending 3 can't displace anyone (3 < 4), so VIP list stays [8, 5, 4]. Minimum VIP spender: 4.
3
Customer Spends 10
Customer spending 10 displaces the minimum VIP spender (4). New VIP list: [10, 8, 5]. New minimum VIP spender: 5.
4
Constant Time Updates
With only 3 VIP spots to manage, checking and updating takes constant time, no matter how many total customers you've seen.
Key Takeaway
๐ŸŽฏ Key Insight: By maintaining only the K largest elements in a min-heap, we can efficiently answer "what's the K-th largest?" in O(log K) time, regardless of how many total elements we've processed!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(log k)

Each add operation involves at most one heap operation (insert/replace) which takes O(log k)

n
2n
โšก Linearithmic
Space Complexity
O(k)

Only store K elements in the min-heap

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค k โ‰ค 104
  • 0 โ‰ค nums.length โ‰ค 104
  • -104 โ‰ค nums[i] โ‰ค 104
  • -104 โ‰ค val โ‰ค 104
  • At most 104 calls will be made to add
  • It is guaranteed that there will be at least k elements in the array when you search for the kth element.
Asked in
Amazon 45 Google 38 Facebook 32 Microsoft 28
89.3K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen