Skip to content

Practice Online Election

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#911
LeetCode Problem

Online Election

Problem Statement

TopVotedCandidate(persons,times) records one vote per timestamp. q(t) returns the leading candidate using all votes at times at most t. When counts tie, the candidate with the most recent vote among the tied candidates wins. Practice approach: Precompute the leader after every vote, updating on greater-or-equal vote counts to preserve the recency tie rule. Binary-search for the last recorded time at most each query. Preprocessing takes O(n), and queries O(log n). Test an exact voting timestamp and a query between votes.

Source: Online Election on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
["TopVotedCandidate","q","q","q","q"]
[[[0,1,0,1],[2,5,9,12]],[4],[5],[10],[12]]
Output
[null,0,1,0,1]
Explanation

The votes at 5 and 12 create ties, each won by candidate 1 as the most recently voted-for tied candidate.

Constraints

1 <= persons.length <= 5000
times.length equals persons.length.
0 <= persons[i] < persons.length
0 <= times[i] <= 10^9; times are strictly increasing.
times[0] <= t <= 10^9
At most 10^4 q calls.

Related LeetCode Problems

Practice more problems similar to Online Election.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.