Top K Frequent Elements in Stream
Beginner Mode

Problem Statement

Design a data structure that processes a stream of integers and can report the k most frequent elements at any point.

Implement the TopKFrequent class:

  • TopKFrequent(int k) initializes the tracker with the target k.
  • void add(int num) processes a new integer from the stream.
  • int[] topK() returns the k most frequent elements seen so far, sorted by frequency in descending order. If two elements have the same frequency, the smaller value comes first. If fewer than k distinct elements have been seen, return all of them.

Additional information

  • 1 <= k <= 1000
  • 0 <= num <= 100,000
  • At most 50,000 calls will be made to add and topK combined.

Example 1:

Input:
["TopKFrequent", "add", "add", "add", "topK", "add", "add", "add", "topK"]
[[2], [1], [1], [2], [], [3], [3], [3], []]

Output: [null, null, null, null, [1, 2], null, null, null, [3, 1]]

Explanation:

  • After adding 1, 1, 2: freq(1)=2, freq(2)=1. Top 2: [1, 2]
  • After adding 3, 3, 3: freq(3)=3, freq(1)=2, freq(2)=1. Top 2: [3, 1]

Example 2:

Input:
["TopKFrequent", "add", "topK"]
[[3], [5], []]

Output: [null, null, [5]]

Explanation: Only one element seen, so topK() returns [5] even though k=3.

Quick Solution

Code Environment

Sign in or try as guest to run your code.

Sign In

Track

Question Difficulty Company Access
Need more practice in this area? Explore more questions →