947. Online Election
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
Method Explanation
This problem requires us to find the leading candidate at various points in time. A crucial observation is that the election's leader can only change at the exact moments when votes are cast. Between any two consecutive vote times, times[i] and times[i+1], the leader remains constant. This suggests a two-phase approach: pre-calculating results in the constructor and then performing fast lookups in the query method q.
Solution
Online Election in Python
import bisect
class TopVotedCandidate:
def __init__(self, persons: List[int], times: List[int]):
# Store times for query lookups
self.times = times
self.leaders = []
counts = {}
leader = -1
max_votes = 0
# Precompute the leader at each time a vote is cast
for p in persons:
counts[p] = counts.get(p, 0) + 1
# If the current person's vote count is >= max_votes, they become the new leader.
# This handles the tie-breaking rule: most recent vote wins.
if counts[p] >= max_votes:
max_votes = counts[p]
leader = p
self.leaders.append(leader)
def q(self, t: int) -> int:
# bisect_right finds an insertion point which comes after (to the right of)
# any existing entries of t. It's equivalent to C++'s upper_bound.
# It finds the index of the first element in self.times that is > t.
idx = bisect.bisect_right(self.times, t)
# The index we want is idx - 1, which corresponds to the latest time <= t.
# Since t >= times[0], idx is at least 1, so idx - 1 is valid.
return self.leaders[idx - 1]
# Your TopVotedCandidate object will be instantiated and called as such:
# obj = TopVotedCandidate(persons, times)
# param_1 = obj.q(t)
Online Election in Java
class TopVotedCandidate {
// Store the leader at each corresponding time in voteTimes
private List<Integer> leaders;
private int[] voteTimes;
public TopVotedCandidate(int[] persons, int[] times) {
voteTimes = times;
int n = persons.length;
leaders = new ArrayList<>(n);
// Since person IDs are in [0, n-1], an array is efficient for counts.
int[] counts = new int[n];
int leader = -1;
int maxVotes = 0;
// Precompute the leader at each time a vote is cast
for (int i = 0; i < n; ++i) {
int p = persons[i];
counts[p]++;
// If the current person's vote count is >= max_votes, they become the new leader.
// This handles the tie-breaking rule: most recent vote wins.
if (counts[p] >= maxVotes) {
maxVotes = counts[p];
leader = p;
}
leaders.add(leader);
}
}
public int q(int t) {
// Binary search to find the index of the first time > t (upper_bound)
int low = 0, high = voteTimes.length;
while (low < high) {
int mid = low + (high - low) / 2;
if (voteTimes[mid] > t) {
high = mid;
} else {
low = mid + 1;
}
}
// 'low' is now the index of the first element strictly greater than t.
// The index we want is low - 1, which corresponds to the latest time <= t.
// Since t >= voteTimes[0], 'low' will be at least 1, so low - 1 is safe.
return leaders.get(low - 1);
}
}
/**
* Your TopVotedCandidate object will be instantiated and called as such:
* TopVotedCandidate obj = new TopVotedCandidate(persons, times);
* int param_1 = obj.q(t);
*/
Online Election in C++
class TopVotedCandidate {
private:
// Store the leader at each corresponding time in times_data
std::vector<int> leaders;
std::vector<int> times_data;
public:
TopVotedCandidate(vector<int>& persons, vector<int>& times) {
// Store times for query lookups
times_data = times;
int n = persons.size();
leaders.reserve(n);
// Since person IDs are in [0, n-1], an array is efficient for counts.
std::vector<int> counts(n, 0);
int leader = -1;
int max_votes = 0;
// Precompute the leader at each time a vote is cast
for (int i = 0; i < n; ++i) {
int p = persons[i];
counts[p]++;
// If the current person's vote count is >= max_votes, they become the new leader.
// This handles the tie-breaking rule: most recent vote wins.
if (counts[p] >= max_votes) {
max_votes = counts[p];
leader = p;
}
leaders.push_back(leader);
}
}
int q(int t) {
// Use binary search (upper_bound) to find the first time > t.
// std::upper_bound returns an iterator to the first element in the range
// that is greater than the given value.
auto it = std::upper_bound(times_data.begin(), times_data.end(), t);
// The index we want is the one just before the returned iterator's position.
// This corresponds to the latest time less than or equal to t.
int idx = std::distance(times_data.begin(), it) - 1;
// The problem guarantees t >= times[0], so idx will be non-negative.
return leaders[idx];
}
};
/**
* Your TopVotedCandidate object will be instantiated and called as such:
* TopVotedCandidate* obj = new TopVotedCandidate(persons, times);
* int param_1 = obj->q(t);
*/
Online Election in TypeScript
class TopVotedCandidate {
private leaders: number[];
private voteTimes: number[];
constructor(persons: number[], times: number[]) {
this.voteTimes = times;
this.leaders = [];
// Since person IDs are in [0, n-1], an array is efficient for counts.
const counts = new Array(persons.length).fill(0);
let leader = -1;
let maxVotes = 0;
// Precompute the leader at each time a vote is cast
for (let i = 0; i < persons.length; i++) {
const p = persons[i];
counts[p]++;
// If the current person's vote count is >= maxVotes, they become the new leader.
// This handles the tie-breaking rule: most recent vote wins.
if (counts[p] >= maxVotes) {
maxVotes = counts[p];
leader = p;
}
this.leaders.push(leader);
}
}
q(t: number): number {
// Binary search to find the index of the first time > t (upper_bound)
let low = 0;
let high = this.voteTimes.length;
while (low < high) {
const mid = Math.floor(low + (high - low) / 2);
if (this.voteTimes[mid] > t) {
high = mid;
} else {
low = mid + 1;
}
}
// 'low' is now the index of the first element strictly greater than t.
// The index we want is low - 1, which corresponds to the latest time <= t.
// Since t >= voteTimes[0], 'low' will be at least 1, so low - 1 is safe.
return this.leaders[low - 1];
}
}
/**
* Your TopVotedCandidate object will be instantiated and called as such:
* var obj = new TopVotedCandidate(persons, times)
* var param_1 = obj.q(t)
*/
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.