Online Election

MediumBinary Searchbinary search

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

An election records one vote at a time: the i-th vote was cast for candidate persons[i] at time times[i], and times is strictly increasing. Implement TopVotedCandidate(persons, times) and q(t), which returns the candidate who was leading at time t. Votes cast exactly at time t count. The leader is the candidate with the most votes so far. If several candidates are tied for the most votes, the leader is the tied candidate who received a vote most recently. Every query satisfies t >= times[0].

Examples

Input: ["TopVotedCandidate","q","q","q","q","q","q"] [[[0,1,1,0,0,1,0],[0,5,10,15,20,25,30]],[3],[12],[25],[15],[24],[8]]
Output: [null,0,1,1,0,0,1]
At t=3 only candidate 0 has a vote. At 12, candidate 1 has 2 votes. At 25 it is 3-3 and candidate 1 voted last. At 15 it is 2-2 with 0 voting last. At 24, candidate 0 leads 3-2. At 8 it is 1-1 and 1 voted last.
Input: ["TopVotedCandidate","q","q","q","q"] [[[2,3,3],[1,4,9]],[1],[4],[9],[3]]
Output: [null,2,3,3,2]
At t=4 the score is 1-1 and 3 received the latest vote. At 9, candidate 3 has 2 votes. At 3 only the first vote exists.

Constraints

  • 1 <= persons.length <= 5000
  • `times.length == persons.length`, 0 <= times[i] <= 10^9, strictly increasing
  • 0 <= persons[i] < persons.length
  • `times[0] <= t <= 10^9`
  • At most 10^4 calls to `q`

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More binary search problems