Skip to main content
Back to problems
#911
Medium Algorithms

Online election

Array Hash Table Binary Search Design
52.7% acceptance
Feb 22, 2026
1085
682
You are given two integer arrays persons and times. In an election, the ith vote was cast for persons[i] at time times[i]. For each query at a time t, find the person that was leading the election at time t. Votes cast at time t will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins. Implement the TopVotedCandidate class: TopVotedCandidate(int[] persons, int[] times) Initializes the object with the persons and times arrays. int q(int t) Returns the number of the person that was leading the election at time t according to the mentioned rules.

Solution

Rust
Time O(n log n)
Space O(n)
LeetCode
solution.rs
* impl TopVotedCandidate {

 *     fn new(persons: Vec<i32>, times: Vec<i32>) -> Self {

 *     }

 *     fn q(&self, t: i32) -> i32 {

 *     }
 * }
 */

/**
 * Your TopVotedCandidate object will be instantiated and called as such:
 * let obj = TopVotedCandidate::new(persons, times);
 * let ret_1: i32 = obj.q(t);
 */

pub struct TopVotedCandidate {
  times: Vec<i32>,
  leaders: Vec<i32>,
}
impl TopVotedCandidate {
  pub fn new(persons: Vec<i32>, times: Vec<i32>) -> Self {
    let n = persons.len();
    let mut votes = std::collections::HashMap::new();
    let mut leaders = vec![0i32; n];
    let mut leader = -1i32;
    for i in 0..n {
      *votes.entry(persons[i]).or_insert(0) += 1;
      if leader == -1 || votes[&persons[i]] >= votes[&leader] { leader = persons[i]; }
      leaders[i] = leader;
    }
    TopVotedCandidate { times, leaders }
  }
  pub fn q(&self, t: i32) -> i32 {
    let pos = self.times.partition_point(|&x| x <= t) - 1;
    self.leaders[pos]
  }
}