1753. Live Mode Tracker

Medium3.5 points estimatedHeapHash TableData Stream

A radio station tracks which song request is most popular as listeners phone in. A multiset of song codes starts empty, and you receive operations in order. If ops[i] = 1, one copy of vals[i] is added to the multiset. If ops[i] = 2, one copy of vals[i] is removed if the multiset contains it; otherwise nothing changes. After every operation, record the value that currently appears the most times; if several values share the highest count, record the smaller value, and if the multiset is empty record -1. Return the recorded values as an int[] of the same length as ops. Aim for O(n log n) time and O(n) space. There are up to 10^5 operations and values reach 10^9.

Example 1

Input:
ops = [1,1,1,2,1], vals = [5,3,3,5,5]
Output:
[5,3,3,3,3]
Explanation:

After the adds the counts evolve as {5:1}, {5:1,3:1}, {5:1,3:2}; removing a 5 leaves {3:2}, then adding 5 gives {3:2,5:1}, so the modes are 5, 3, 3, 3, 3.

Example 2

Input:
ops = [2,1,2,2], vals = [4,4,4,4]
Output:
[-1,4,-1,-1]
Explanation:

Removing from an empty set does nothing (-1); adding 4 gives mode 4; removing it empties the set (-1); the last removal again does nothing (-1).

Constraints

1 ≤ n ≤ 105 where n = ops.length = vals.length; ops[i] is 1 or 2; 1 ≤ vals[i] ≤ 109.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,400 msC++ 600 msJava 1,200 msJavaScript 1,200 msTypeScript 1,200 ms

Expected complexity

Time
O(n log n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…