Maintain k-th largest in a stream
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Design and implement a class KthLargest that, given an integer k and an initial list of integers, supports:
(
1) KthLargest(k, nums): constructor;
(
2) add(val): adds val to the data structure and returns the current k-th largest element. Achieve O(log k) time per insertion and O(k) space. Describe your data structures, handle duplicates, and analyze complexity.
Quick Answer: This question evaluates understanding of data structures and streaming algorithms for maintaining k-th order statistics under dynamic inserts, emphasizing time-space trade-offs and correct handling of duplicates.
Initialize with nums, then after each added value return the current k-th largest element using a min-heap of size k.
Constraints
- Inputs are provided as Python literals matching the function signature.
- Return a deterministic exact-match result.
Examples
Input: (3, [4,5,8,2], [3,5,10,9,4])
Expected Output: [4, 5, 5, 8, 8]
Explanation: Classic sequence.
Input: (1, [], [2,1])
Expected Output: [2, 2]
Explanation: Largest so far.
Hints
- Choose a representation that makes the core operation simple.
- Handle empty and boundary inputs before the main algorithm.