Skip to main content
LeetCode 911, Medium. Topics: Array, Hash Table, Binary Search, Design. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 16 parametrized pytest cases, and a playground notebook:

Problem

You are given two integer arrays persons and times. In an election, the i-th 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.

Examples

Constraints

  • 1 <= persons.length <= 5000
  • times.length == persons.length
  • 0 <= persons[i] < persons.length
  • 0 <= times[i] <= 10^9
  • times is sorted in a strictly increasing order.
  • times[0] <= t <= 10^9
  • At most 10^4 calls will be made to q.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026