1057. Election Leader at Time

A student council runs an online ballot. The vote with index i was cast for candidate persons[i] at moment times[i], and the moments are strictly increasing. Organisers like to ask, after the fact, who was in front at a given moment.

Implement ElectionLeader. q(t) returns the candidate with the most votes among the votes cast at moments <= t. If several candidates share the highest count, the one who received the most recent vote among them is the leader. Pre-process in O(n) and answer each query in O(log n); you may assume t is never earlier than times[0].

Example 1

Input:
operations = ["ElectionLeader","q","q","q","q","q"]arguments = [[[5,7,7,5,5],[10,20,30,40,50]],[10],[25],[35],[40],[60]]
Output:
[null,5,7,7,5,5]
Explanation:

At time 25 persons 5 and 7 each have one vote and 7 voted more recently; at time 40 the 2-2 tie goes to 5, whose vote came last.

Example 2

Input:
operations = ["ElectionLeader","q","q","q"]arguments = [[[3],[100]],[100],[101],[1000000000]]
Output:
[null,3,3,3]
Explanation:

With one vote cast, person 3 leads from time 100 onwards.

Example 3

Input:
operations = ["ElectionLeader","q","q","q","q","q"]arguments = [[[1,2,3,1],[2,4,6,8]],[2],[3],[5],[7],[8]]
Output:
[null,1,1,2,3,1]
Explanation:

Every candidate ties at one vote so the newest voter leads, until the second vote for 1 gives it the lead outright at time 8.

Constraints

1 ≤ persons.length = times.length ≤ 5000

0 ≤ persons[i] ≤ 109, 0 ≤ times[i] ≤ 109, times strictly increasing

times[0] ≤ t ≤ 109, at most 5000 queries

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Input
Each case is an operation log. operations names the class first and then each method call; arguments holds the arguments for each, in the same order. Your answer is one list with a result per operation - null for the constructor and for methods that return nothing.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n) build, O(log n) per query
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…

operations names the class, then each method to call; arguments holds one list of arguments per operation, in the same order.