FastPrepDynamic Top K Frequent Elements

Dynamic Top K Frequent Elements

Bloomberg LP logoBloomberg LP● MediumNEW GRADPHONE SCREENONSITE INTERVIEW
Learn

Problem statement

Maintain a multiset of integer values. It starts empty and receives the rows of operations in order:

  • [1, value] inserts one occurrence of value.
  • [2, value] deletes one occurrence of value. Every delete is valid when it occurs.
  • [3, k] requests the current k most frequent distinct values.

For a top-k request, rank values by decreasing frequency. If two values have the same frequency, rank the smaller value first. Return one result row for each top-k request, in request order.

Function

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

Examples

Example 1

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

At the first query, 3 and 5 both have frequency 2, so the smaller value comes first. After deleting one 3, value 5 has frequency 2; values 2 and 3 tie at frequency 1, so 2 takes the second position.

Example 2

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

After one deletion, both remaining values have frequency 1. The numeric tie-break places -1 before 4.

Example 3

operations = [[1,7],[1,7],[1,8],[2,7],[2,7],[3,1]]return = [[8]]

Both occurrences of 7 are removed, so only 8 remains when the query is processed.

Constraints

  • 1 <= operations.length <= 100000.
  • Every row of operations has exactly two integers.
  • Operation codes are 1, 2, or 3.
  • Inserted and deleted values are between -10^9 and 10^9.
  • Every delete names a value whose current frequency is positive.
  • Every top-k request satisfies 1 <= k <= the number of currently distinct values.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int[][] dynamicTopK(int[][] operations) {
    // Write your code here.
}
operations[[1,5],[1,3],[1,5],[1,2],[1,3],[3,2],[2,3],[3,2]]
expected[[3,5],[5,2]]
Checking account…