Problem Description
You are given two integer arrays persons and times. The i-th vote was cast for persons[i] at time times[i]. For each query at a time t, determine the person who was leading the election at time t. Votes cast at time t count towards the query, and in the case of a tie, the most recent vote wins.
Key Insights
- Precompute the leader at each vote time.
- Use a hash table to count votes per candidate while iterating through the persons array.
- Maintain a leaders list that records the current leader at each corresponding vote time.
- Use binary search on the times array to efficiently answer queries for any time t.
Space and Time Complexity
Time Complexity: O(n + q log n), where n is the number of votes and q is the number of queries. Space Complexity: O(n), to store the leaders for each vote and the counts for each candidate.
Solution
We process the vote records sequentially, tracking vote counts in a hash table and updating the current leader when a candidate's vote count is equal to or exceeds that of the current leader. This leader is saved along with each vote time. For each query, binary search is used on the times array to find the last vote time that is less than or equal to the query time, and the leader corresponding to that time is returned.