Leetcode 703: Kth Largest Element in a Stream

grid47
grid47
Exploring patterns and algorithms
Aug 28, 2024 6 min read

A stream of numbers where the kth largest element is identified, glowing brightly as it’s found.
Solution to LeetCode 703: Kth Largest Element in a Stream Problem

You are tasked with implementing a class that helps track the kth highest score in a dynamic list of test scores. Each time a new score is submitted, you need to return the kth highest score in the list.
Problem
Approach
Steps
Complexity
Input: The class should be initialized with an integer k (the desired ranking) and a list of test scores. For each new score added to the stream, return the kth highest score in the list.
Example: KthLargest kthLargest = new KthLargest(2, [1, 3, 5, 7, 9]); kthLargest.add(6);
Constraints:
• 0 <= nums.length <= 10^4
• 1 <= k <= nums.length + 1
• -10^4 <= nums[i] <= 10^4
• -10^4 <= val <= 10^4
• At most 10^4 calls will be made to the add method.
Output: The method should return the kth largest number in the list after each new score is added.
Example: Output: [null, 5, 6, 7, 7]
Constraints:
• The result after each call to add should be the kth largest score in the current list of test scores.
Goal: Track the kth largest score dynamically using a priority queue or a min-heap to efficiently maintain the list of the top k scores.
Steps:
• 1. Initialize a priority queue (min-heap) to store the top k elements.
• 2. Add each score to the heap.
• 3. If the heap exceeds k elements, remove the smallest element.
• 4. After each addition, the top of the heap will be the kth largest score.
Goal: The problem must handle dynamic updates to the list of scores.
Steps:
• The class must handle multiple calls to the add method efficiently.
• The list of scores can vary in size from 0 to 10,000.
Assumptions:
• The list will be dynamically updated with new scores.
• The kth largest element should be returned after each new score is added.
Input: Input: KthLargest(2, [1, 3, 5, 7, 9])
Explanation: When the 2nd largest element is requested after each new score is added, the following occurs: add(6) => 6 becomes the 2nd largest number, add(8) => 7 becomes the 2nd largest number, etc.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus