Live Poll Leaderboard: Track the Current Front-Runner
Data Structure DesignAuto-graded · 16 test casesLast updated
Process a batch of vote and leader-query operations over named options, using counters and a tie-break rule to report the current leader after each query efficiently.
Live Poll Leaderboard
A dining app lets people vote for their favorite venues. You are given a recorded sequence of operations to replay against an initially empty poll, and you must report what each operation produces.
Implement a function that takes two parallel lists:
operations: each entry is a string, either"vote"or"get_top_restaurant".arguments:arguments[i]is the list of arguments foroperations[i].- For
"vote", it is a one-element list[name], wherenameis the venue receiving one more vote. - For
"get_top_restaurant", it is an empty list[].
- For
Behavior
- A
"vote"adds one vote to the named venue. A venue seen for the first time starts with zero votes and then receives this vote, so its total becomes 1. - A
"get_top_restaurant"asks for the venue that currently has the most votes.- If several venues share the highest vote count, the answer is the one whose name comes first in lexicographic (alphabetical) order.
- If no votes have been cast so far, the answer is
None.
- Any operation name other than these two must raise a
ValueError.
Output
Return a list with exactly one entry per operation, in order:
Nonefor each"vote".- For each
"get_top_restaurant", the name of the current leader as a string, orNoneif there are no votes yet.
Constraints
len(operations) == len(arguments).- Venue names consist of lowercase English letters (and may include underscores, as in the samples).
- The number of
"vote"operations can be up to 1,000,000. - There are at most 10,000 distinct venues.
- Leader queries may be interleaved with votes, possibly after every single vote, so re-scanning every venue on each query may be too slow.
Examples
Example 1
Input: poll_leaderboard(['vote', 'vote', 'vote', 'get_top_restaurant'], [['pizza_hut'], ['burger_king'], ['pizza_hut'], []])
Output: [None, None, None, 'pizza_hut']
Example 2
Input: poll_leaderboard(['vote', 'vote', 'get_top_restaurant'], [['b'], ['a'], []])
Output: [None, None, 'a']
Hints
Hint 1
Keep a dictionary from venue name to its current vote total so each vote is a constant-time update.
Hint 2
Votes only ever increase a count. Think about which venue can possibly become the new leader right after a single vote.
Hint 3
Alternatively, use a min-heap of (-count, name) entries; when a venue's count changes, push a new entry and discard outdated ones only when they reach the top.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Maintain two structures while replaying the operations:
- A dictionary
countsmapping each venue to its current vote total, so a vote is an O(1) update. - A min-heap of tuples
(-count, name). Negating the count makes the smallest tuple correspond to the highest vote total, and when counts are equal, Python compares the names, so the lexicographically smaller name comes out first. That is exactly the required tie-break.
Heaps cannot update an existing entry. So on every vote we push a fresh entry with the venue's new count and leave the old one behind as a stale entry.
On a leader query, we look at the heap top. If its stored count differs from counts[name], it is stale, so we pop it. We repeat until the top matches the real count (or the heap is empty). The top is then the answer, or None if the heap is empty.
Why it is correct
- Every venue's latest count is always present in the heap, because each vote pushes it.
- Counts only increase, so any older entry for a venue has a smaller count than the current one and can never match again. Stale entries are therefore reliably detected.
- After removing stale entries from the top, the top is the minimum
(-count, name)among valid entries, which is the maximum count with the smallest name among ties. Stale entries deeper in the heap cannot affect this answer. - An empty heap means no votes were cast, so
Noneis returned. - Any unrecognized operation raises
ValueError.
Complexity
Let V be the number of votes and Q the number of queries.
- Each vote costs O(log V) for the push.
- Each entry is popped at most once overall, so total query work is amortized O((V + Q) log V).
- Space is O(U + V), where U is the number of distinct venues (the heap dominates).
Alternative
Because counts only grow, only the venue just voted for can take over the lead. Keeping (leader, best_count) and comparing the updated venue against it (higher count wins, or equal count with a smaller name) gives O(1) per operation and O(U) space. The heap approach is still useful as it extends to top-k queries and to decrements.
Reference solution
import heapq
from typing import List, Optional
def poll_leaderboard(operations: List[str], arguments: List[List[str]]) -> List[Optional[str]]:
counts = {}
heap = []
results = []
for operation, args in zip(operations, arguments):
if operation == "vote":
name = args[0]
counts[name] = counts.get(name, 0) + 1
heapq.heappush(heap, (-counts[name], name))
results.append(None)
elif operation == "get_top_restaurant":
while heap and counts.get(heap[0][1]) != -heap[0][0]:
heapq.heappop(heap)
results.append(heap[0][1] if heap else None)
else:
raise ValueError("unknown operation")
return results