Online Election - Problem

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.

Input & Output

Example 1 — Basic Election Tracking
$ Input: persons = [0,1,1,0,0,1,0], times = [0,5,10,15,20,25,30], queries = [3,12,25,15,24,8]
Output: [0,1,1,0,0,1]
💡 Note: At time 3: person 0 leads (1-0). At time 12: person 1 leads (2-1). At time 25: person 1 leads (3-3, but person 1 voted most recently). At time 15: person 0 leads (2-2, but person 0 voted most recently at time 15).
Example 2 — Early Query
$ Input: persons = [0,1,1,0], times = [0,5,10,15], queries = [2,8]
Output: [0,1]
💡 Note: At time 2: only person 0 has voted. At time 8: person 1 leads 2-1.
Example 3 — Tie Breaking
$ Input: persons = [0,1,0,1], times = [0,5,10,15], queries = [10,15]
Output: [0,1]
💡 Note: At time 10: tie 2-2, person 0 voted most recently at time 10. At time 15: tie 2-2, person 1 voted most recently at time 15.

Constraints

  • 1 ≤ persons.length ≤ 5000
  • times.length == persons.length
  • 0 ≤ persons[i] ≤ 999
  • 1 ≤ times[i] ≤ 109
  • times is sorted in a strictly increasing order
  • 1 ≤ queries.length ≤ 104
  • 1 ≤ queries[i] ≤ 109

Visualization

Tap to expand
Online Election: Track Leading CandidateVotes Timeline:0110t=0t=5t=10t=15Leader Status:0110Query: Who was leading at time 12?Answer: Person 1 (last known leader ≤ time 12)
Understanding the Visualization
1
Input
Vote sequence with persons and times
2
Process
Track leader changes as votes come in
3
Query
Find leader at specific query times
Key Takeaway
🎯 Key Insight: Precompute leadership changes and binary search for efficient query answering
Asked in
Google 15 Facebook 12 Microsoft 8
28.0K Views
Medium Frequency
~25 min Avg. Time
1.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen