Dynamic Top K Frequent Elements
Problem statement
Maintain a multiset of integer values. It starts empty and receives the rows of operations in order:
[1, value]inserts one occurrence ofvalue.[2, value]deletes one occurrence ofvalue. Every delete is valid when it occurs.[3, k]requests the currentkmost 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
operationshas exactly two integers. - Operation codes are
1,2, or3. - Inserted and deleted values are between
-10^9and10^9. - Every delete names a value whose current frequency is positive.
- Every top-k request satisfies
1 <= k <=the number of currently distinct values.