← 返回 snapchat 的题目列表Design a Stream Top-K Class (Online Top-K Elements/Frequencies)
类型:online_judge
Problem: Design a Top-K Class for a Data Stream
You are given an unbounded stream of incoming elements. Design and implement a class that can report the current Top K elements at any time.
Implement the following interface (pseudocode):
class TopKStream:
TopKStream(int k)
void add(int x)
List<int> topk()
Requirements
TopKStream(k): initialize the structure with k.
add(x): ingest an element x (duplicates allowed).
topk(): return the k most frequent elements seen so far.
Rules
If fewer than k distinct elements exist, return all distinct elements.
If frequencies tie, break ties by smaller element value first (unless the interviewer specifies a different rule).
add() can be called very frequently; topk() can be called at arbitrary times.
Constraints (to guide complexity)
Up to 10^6 calls to add()
Values are 32-bit signed integers
Discuss scalable time/space complexity for both operations.
Example
For k = 2:
Operations:
add(1)
add(1)
add(2)
add(3)
add(2)
topk()
Frequencies: 1->2, 2->2, 3->1
Return: [1, 2] (frequency desc; value asc for ties).
Example
Input
k=2
ops=add 1, add 1, add 2, add 3, add 2, topk
Output
[1, 2]