Implement Data Structure for Top-K Elements in Streams
Company: Pinterest
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: This question evaluates competency in streaming algorithms, dynamic data structures for maintaining top-K elements in real time, and scalability considerations for handling large or distributed input streams.
Constraints
- 1 <= len(operations) <= 200000
- -10^9 <= x <= 10^9 for any added value
- 0 <= k <= 100000
- operations[i] is either ['add', x] or ['get']
- Return one list per 'get' operation, each sorted in descending order
- Use O(k) additional space
Hints
- Maintain a min-heap of size at most K: push until size K; thereafter, replace the heap minimum only if the new value is larger.
- For 'get', copy and sort the heap in descending order to return the current top-K.
- For very large K or distributed streams, keep local top-K min-heaps on shards and merge them with a min-heap or k-way merge; for approximate heavy hitters, consider Count-Min Sketch.