Problem · Hash Table

Streaming Top-K Frequent Elements

Learn this problem
MediumNvidia logoNvidiaFULLTIMEPHONE SCREEN

Problem statement

Process a finite sequence of streaming operations. Each operation is one of:

  • [0, value]: add one occurrence of value to the stream.
  • [1, k]: return the k distinct values with the highest frequencies among all values added so far.

For every query, order values by decreasing frequency. When frequencies tie, order the smaller value first. Return one row per query, in query order.

Design the update path around frequency buckets rather than maintaining a size-k heap for every query.

Function

streamTopK(operations: int[][]) → int[][]

Examples

Example 1

operations = [[0,4],[0,2],[0,4],[1,2],[0,2],[0,3],[1,3]]return = [[4,2],[2,4,3]]

The first query sees frequencies 4:2 and 2:1. At the second query, 2 and 4 tie at two occurrences, so 2 comes first.

Example 2

operations = [[0,5],[0,3],[0,5],[0,3],[1,1],[0,3],[1,2]]return = [[3],[3,5]]

The first query breaks a frequency tie by value. The later update makes 3 strictly more frequent than 5.

Example 3

operations = [[0,-1],[0,7],[0,-1],[0,7],[0,5],[1,3]]return = [[-1,7,5]]

Values -1 and 7 tie at frequency two and appear in ascending numeric order before 5.

Constraints

  • 1 <= operations.length <= 5000.
  • Every operation contains exactly two integers.
  • Add values satisfy -10^9 <= value <= 10^9.
  • Each query satisfies 1 <= k <= the number of distinct values added before that query.
  • At least one operation is a query.

More Nvidia problems

drafts saved locally
public int[][] streamTopK(int[][] operations) {
    // Write your code here.
}
operations[[0,4],[0,2],[0,4],[1,2],[0,2],[0,3],[1,3]]
expected[[4,2],[2,4,3]]
checking account