Leetcode 911: Online Election

grid47
grid47
Exploring patterns and algorithms
Aug 7, 2024 5 min read

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 given time t, you need to return the person who was leading the election at time t. If there is a tie between candidates, the most recent vote wins.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer array `persons` and an integer array `times`.
Example: Input: persons = [0, 1, 1, 0, 0, 1, 0], times = [0, 5, 10, 15, 20, 25, 30]
Constraints:
• 1 <= persons.length <= 5000
• times.length == persons.length
• 0 <= persons[i] < persons.length
• 0 <= times[i] <= 10^9
• times is sorted in strictly increasing order
• times[0] <= t <= 10^9
• At most 10^4 queries will be made
Output: For each query at time `t`, return the person who was leading the election at that time, based on the most recent vote or tie-breaking rules.
Example: Output: [null, 0, 1, 1, 0, 0, 1]
Constraints:
• The output should be the person leading the election at the specified query time.
Goal: The goal is to track the current leader after each vote and quickly determine the leader at any given query time `t`.
Steps:
• Iterate through the `persons` array to record the vote counts for each person, and track the leader at each time point.
• For each query, find the most recent time that is less than or equal to the query time `t` and return the person who was leading at that time.
Goal: The input arrays have size constraints, and the times are guaranteed to be sorted.
Steps:
• The array lengths will be at most 5000, and there will be no more than 10^4 queries.
Assumptions:
• The times array is strictly increasing, meaning that each query time will be greater than or equal to the previous query time.
Input: Input: persons = [0, 1, 1, 0, 0, 1, 0], times = [0, 5, 10, 15, 20, 25, 30]
Explanation: At time 0, person 0 is leading. At time 5, person 1 takes the lead. At time 10, person 1 is still leading. At time 15, person 0 takes the lead again. At time 20, person 0 is leading. At time 25, person 1 is leading. At time 30, person 1 is still leading.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus