Real-Time Restaurant Vote Leaderboard
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Design an in-memory leaderboard VotingSystem that tracks diner ballots and reports the leading restaurant at any moment, along with the runner function voting_system(operations, arguments) used to evaluate sequences of calls.
Support two operations on a single VotingSystem instance:
vote(restaurant_name: str) -> None: Adds1ballot torestaurant_name(starting at1the first time that name appears). Invoting_system, each"vote"entry hasarguments[i] = [restaurant_name]and producesNoneat indexiof the returned list.get_top_restaurant() -> Optional[str]: Returns the restaurant currently holding the highest ballot count:- If multiple restaurants share the highest ballot count, break the tie by returning the name that comes earliest in standard lexicographical (alphabetical) order (for instance,
"bistro"precedes"diner", and"grill"precedes"grillhouse"). - If zero ballots have been recorded so far, return
None. - In
voting_system, each"get_top_restaurant"entry hasarguments[i] = []and appends the returned value at indexiof the output list.
- If multiple restaurants share the highest ballot count, break the tie by returning the name that comes earliest in standard lexicographical (alphabetical) order (for instance,
Note that get_top_restaurant() may be invoked after every single ballot, so queries must remain fast under heavy traffic.
Examples
Example 1
Input:
operations = ["vote", "vote", "vote", "get_top_restaurant"]
arguments = [["ramen"], ["falafel"], ["ramen"], []]
Output:
[None, None, None, "ramen"]
Explanation: "ramen" accumulates 2 ballots while "falafel" has 1, making "ramen" the sole leader when get_top_restaurant runs.
Example 2
Input:
operations = [
"get_top_restaurant",
"vote",
"vote",
"get_top_restaurant",
"vote",
"get_top_restaurant"
]
arguments = [[], ["diner"], ["bistro"], [], ["diner"], []]
Output:
[None, None, None, "bistro", None, "diner"]
Explanation:
- The initial query runs before any ballot arrives and returns None.
- After "diner" and "bistro" each receive 1 ballot, "bistro" wins the 1-to-1 tie because "bistro" < "diner" alphabetically.
- A second ballot for "diner" raises its count to 2, moving "diner" ahead of "bistro".
Constraints
1 <= len(operations) == len(arguments) <= 1,000,000- At most
10,000distinctrestaurant_namevalues appear across the input. - Each
restaurant_nameis a non-empty string of lowercase ASCII characters. - Every entry in
operationsis either"vote"or"get_top_restaurant".
Step-by-step walkthrough
Understand the problem and tie-breaking rule
We need to build a live voting counter for restaurants with two operations:
vote(restaurant_name): adds1vote torestaurant_name(starting at1if this is its first vote).get_top_restaurant(): returns the restaurant with the highest vote count right now.- Tie-breaker: if two or more restaurants share the highest count, return the one that comes first in lexicographical order (standard alphabetical dictionary order, comparing character by character from left to right, so
"a" < "b"and"ab" < "abc"). - Empty state: if no votes have been cast yet, return
None(matching theOptional[str]return type).
- Tie-breaker: if two or more restaurants share the highest count, return the one that comes first in lexicographical order (standard alphabetical dictionary order, comparing character by character from left to right, so
The judge calls
voting_system(operations, arguments)and expects one output per call:Nonefor each"vote"call, and the leading restaurant name (orNone) for each"get_top_restaurant"call.Pay attention to the scale in the constraints: up to
1,000,000votes across up to10,000unique restaurants, withget_top_restaurant()potentially called after every single vote.Why recounting on every query is too slow
A natural first idea is to store a dictionary
votes[name] = countsovoteisO(1), and then scan the entire dictionary insideget_top_restaurant()to find the best(count, name)pair.That works on tiny inputs, but let
Ube the number of unique restaurants (U <= 10,000) andNbe the number of operations (N <= 1,000,000). Ifget_top_restaurant()runs after every vote, scanning10,000entries1,000,000times takes roughly10,000 * 1,000,000 = 10^10comparisons — seconds or minutes instead of milliseconds. Sorting the dictionary on every query (O(U log U)) is slower still.To handle queries after every vote effortlessly, we want
get_top_restaurant()to run inO(1)time.Key idea: maintain the leader incrementally on each vote
Ask what actually changes during a single call to
vote(restaurant_name):- Exactly one restaurant (
restaurant_name) changes its vote count, and that count goes up by 1. - Every other restaurant keeps the exact same count it had a moment ago.
Because counts never go down, no untouched restaurant can suddenly overtake the current leader. The only candidate that can take over the #1 spot — or extend its existing lead — is
restaurant_nameitself!Before vote(X): winner = W (max_votes = M) beats every other restaurant During vote(X): X's count becomes new_count; everyone else is unchanged Case 1: winner is None -> X becomes the first winner Case 2: new_count > M -> X overtakes W (or W extends its own lead!) Case 3: new_count == M and X < W -> X ties W in votes and wins alphabetically Case 4: new_count < M, or tie with X >= W -> W stays the winnerLook closely at Case 2 when
Xis alreadywinner: itsnew_countbecomesM + 1 > M, so Case 2 updatesmax_votestoM + 1automatically! Keeping just two extra fields —self.winnerandself.max_votes— makes bothvoteandget_top_restaurantrun inO(1)time.- Exactly one restaurant (
Implement the VotingSystem class
Let's put the leader comparison in a dedicated helper
_should_become_winnerso each rule reads like plain English:self.votesmaps each restaurant name to its integer vote total._should_become_winnerchecks the three winning conditions in order: no winner yet, strictly higher vote count, or tied vote count with a smaller name.get_top_restaurantsimply returnsself.winner.
class VotingSystem: def __init__(self) -> None: # votes: dict mapping restaurant_name -> total votes, e.g. {"ramen": 2, "falafel": 1} self.votes: Dict[str, int] = {} # winner: name of the current top restaurant, or None before the first vote is cast self.winner: Optional[str] = None # max_votes: vote count belonging to self.winner (0 before any vote is cast) self.max_votes: int = 0 def _should_become_winner(self, restaurant_name: str, new_count: int) -> bool: """Return True if restaurant_name with new_count votes beats the current winner.""" # Before any vote has been recorded, the very first voted restaurant takes the lead. if self.winner is None: return True # Strictly more votes always wins (this also updates max_votes when the leader gets a vote). if new_count > self.max_votes: return True # On a tie, break ties by smaller alphabetical (lexicographical) order, e.g. "bistro" < "diner". if new_count == self.max_votes and restaurant_name < self.winner: return True return False def vote(self, restaurant_name: str) -> None: # Phase 1: Increment this restaurant's running total (initializing missing names to 0 + 1 = 1). previous_count = self.votes.get(restaurant_name, 0) new_count = previous_count + 1 self.votes[restaurant_name] = new_count # Phase 2: Update the cached leader. Because vote counts only ever go up and no other # restaurant's count changed, only restaurant_name can possibly take or extend the lead. if self._should_become_winner(restaurant_name, new_count): self.winner = restaurant_name self.max_votes = new_count def get_top_restaurant(self) -> Optional[str]: # Return the precomputed leader in O(1) time (None if no votes have been cast yet). return self.winnerNotice why
new_count == self.max_votes and restaurant_name < self.winneris essential: if"diner"votes first (1vote) and"bistro"votes second (1vote),"bistro"catches up to a tie rather than exceedingmax_votes, and must still take over the lead because"bistro" < "diner".Wire up the operation runner and trace the tricky cases
The wrapper function
voting_systemcreates oneVotingSystem, loops over(operation, args)pairs, and appendsNonefor"vote"or the top restaurant for"get_top_restaurant".def voting_system(operations: List[str], arguments: List[List[str]]) -> List[Optional[str]]: # Replay the sequence of method calls against a single VotingSystem instance. system = VotingSystem() results: List[Optional[str]] = [] for operation, args in zip(operations, arguments): if operation == "vote": restaurant_name = args[0] system.vote(restaurant_name) results.append(None) elif operation == "get_top_restaurant": results.append(system.get_top_restaurant()) else: raise ValueError(f"Unknown operation: {operation}") return resultsLet's trace Example 2 (
get_top_restaurant(),vote("diner"),vote("bistro"),get_top_restaurant(),vote("diner"),get_top_restaurant()):Step Call votes winner max_votes Why? ---- ---------------------- ----------------------------- --------- --------- ------------------------------------------------- 0 init {} None 0 No votes yet 1 get_top_restaurant() {} None 0 Returns None 2 vote("diner") {"diner": 1} "diner" 1 First vote ever (winner was None) 3 vote("bistro") {"diner": 1, "bistro": 1} "bistro" 1 Tie (1 == 1) and "bistro" < "diner" -> "bistro" 4 get_top_restaurant() {"diner": 1, "bistro": 1} "bistro" 1 Returns "bistro" 5 vote("diner") {"diner": 2, "bistro": 1} "diner" 2 2 > 1 -> "diner" retakes the lead 6 get_top_restaurant() {"diner": 2, "bistro": 1} "diner" 2 Returns "diner"Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple class VotingSystem: def __init__(self) -> None: # votes: dict mapping restaurant_name -> total votes, e.g. {"ramen": 2, "falafel": 1} self.votes: Dict[str, int] = {} # winner: name of the current top restaurant, or None before the first vote is cast self.winner: Optional[str] = None # max_votes: vote count belonging to self.winner (0 before any vote is cast) self.max_votes: int = 0 def _should_become_winner(self, restaurant_name: str, new_count: int) -> bool: """Return True if restaurant_name with new_count votes beats the current winner.""" # Before any vote has been recorded, the very first voted restaurant takes the lead. if self.winner is None: return True # Strictly more votes always wins (this also updates max_votes when the leader gets a vote). if new_count > self.max_votes: return True # On a tie, break ties by smaller alphabetical (lexicographical) order, e.g. "bistro" < "diner". if new_count == self.max_votes and restaurant_name < self.winner: return True return False def vote(self, restaurant_name: str) -> None: # Phase 1: Increment this restaurant's running total (initializing missing names to 0 + 1 = 1). previous_count = self.votes.get(restaurant_name, 0) new_count = previous_count + 1 self.votes[restaurant_name] = new_count # Phase 2: Update the cached leader. Because vote counts only ever go up and no other # restaurant's count changed, only restaurant_name can possibly take or extend the lead. if self._should_become_winner(restaurant_name, new_count): self.winner = restaurant_name self.max_votes = new_count def get_top_restaurant(self) -> Optional[str]: # Return the precomputed leader in O(1) time (None if no votes have been cast yet). return self.winner def voting_system(operations: List[str], arguments: List[List[str]]) -> List[Optional[str]]: # Replay the sequence of method calls against a single VotingSystem instance. system = VotingSystem() results: List[Optional[str]] = [] for operation, args in zip(operations, arguments): if operation == "vote": restaurant_name = args[0] system.vote(restaurant_name) results.append(None) elif operation == "get_top_restaurant": results.append(system.get_top_restaurant()) else: raise ValueError(f"Unknown operation: {operation}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Imagine running a live scoreboard at a busy food festival: instead of emptying and recounting all 10,000 ballot boxes every time someone glances up at the screen, you keep one sticky note next to the stage showing (current champion, champion's score). Whenever a booth receives a new vote, only that single booth's total increases, so no other booth could possibly jump into first place. We simply compare that booth's updated count against the sticky note — checking if it has strictly more votes, or the exact same number of votes with an earlier name in lexicographical order (standard alphabetical dictionary order, comparing characters left to right so "a" < "b" and "ab" < "abc"). Keeping that sticky note accurate after every vote is an invariant (a rule about our stored state that stays true before and after every single operation).
Why does the obvious recount-on-query approach fall short? Storing counts in a dictionary and scanning every entry inside get_top_restaurant() takes up to 10,000 comparisons per query. When get_top_restaurant() is called right after each of 1,000,000 votes, those scans multiply to 10,000,000,000 comparisons and time out. Sorting all restaurants on every query is even slower because it re-orders thousands of unchanged booths again and again.
Here is a tiny 4-step walkthrough showing how the cached (winner, max_votes) handles a tie-breaker and a later overtake (matching Example 2):
Initial state: votes = {}, winner = None, max_votes = 0
1. vote("diner") -> votes = {"diner": 1}, winner = "diner", max_votes = 1 (first vote)
2. vote("bistro") -> votes = {"diner": 1, "bistro": 1}, winner = "bistro", max_votes = 1 (tie 1 == 1, "bistro" < "diner")
3. vote("diner") -> votes = {"diner": 2, "bistro": 1}, winner = "diner", max_votes = 2 (2 > 1, "diner" overtakes)
4. get_top_restaurant -> returns "diner" immediately without scanning votes
Complexity
Let N be the total number of operations, U be the number of unique restaurants (U <= 10,000), and L be the maximum length of a restaurant name.
vote(restaurant_name)—O(1)average time (O(L)if counting string hashing and character-by-character comparison): We do one hash map lookup and update inself.votes, followed by at most one string comparisonrestaurant_name < self.winner.get_top_restaurant()—O(1)time: We return the storedself.winnerattribute directly with zero loops or lookups.- Total time across
Noperations —O(N)average: Each operation performs a constant number of dictionary and variable updates. - Space —
O(U)for the counter state (plusO(N)for the output list returned byvoting_system):self.votesstores one key-value pair per unique restaurant seen so far, whileself.winnerandself.max_votestakeO(1)extra space.
Edge cases
- Query before any vote is cast:
self.winnerstarts asNone, soget_top_restaurant()cleanly returnsNone. - Very first vote:
self.winner is Nonetriggers immediately, settingself.winnerto that restaurant andself.max_votesto1. - Smaller name catching up later: If
"b"reaches2votes first and"a"reaches2votes later,new_count == self.max_votes and "a" < "b"switchesself.winnerto"a". - Larger name catching up later: If
"a"has1vote and"z"reaches1vote,"z" < "a"isFalse, so"a"stays on top until"z"reaches2votes. - Current winner receives another vote:
new_countbecomesself.max_votes + 1, sonew_count > self.max_votestriggers and advancesself.max_votesalongsideself.votes. - Prefix names on a tie: For
"ab"versus"abc"with equal votes, Python's<operator compares prefixes shorter-first ("ab" < "abc"), matching dictionary order.
Common mistakes
- Updating
winneronly whennew_count > self.max_votes: Forgetting thenew_count == self.max_votes and restaurant_name < self.winnerbranch breaks Example 2, where"diner"votes first and"bistro"ties it afterward. - Forgetting to update
max_voteswhen the existingwinnergets another vote: If"diner"votes twice (votes["diner"] == 2) whilemax_votesstays stuck at1, a single vote for"bistro"falsely looks like a1 == 1tie and lets"bistro"steal the lead with fewer votes. - Scanning or sorting
self.votesinsideget_top_restaurant(): Turns anO(1)read intoO(U)orO(U log U), timing out when queries are interleaved with a million votes. - Assuming the cached-winner trick still works if votes can be removed: Our
O(1)shortcut relies on counts only moving upward; if anunvotemethod existed, the leader's count could drop below a runner-up we didn't track.
Alternative approaches
- Compute on demand (
O(1)vote,O(U)query): Only updateself.votesinvote, and scanself.votesinsideget_top_restaurant(). This writes slightly less state on each vote and is fine when queries happen once an hour, but loses badly when queries happen after every vote. - Ordered set / balanced binary search tree (
O(log U)vote,O(1)query): A balanced binary search tree (a tree structure that automatically keeps items sorted while supporting insertions and deletions in logarithmic time, similar tosortedcontainers.SortedListin Python) keyed by(-votes, name)keeps every restaurant ranked at all times. For tracking just the single #1 winner with non-decreasing votes it is unnecessary work, though it becomes the right choice if votes can be cancelled or if we need the topkrestaurants continuously.
Follow-up questions
- How would you adapt the class to support a
get_top_k_restaurants(k)query returning the top k restaurants in ranked order? Ifget_top_k_restaurants(k)is called infrequently, keepvoteatO(1)and use a min-heap (a binary tree stored in an array that efficiently tracks thekbest items) viaheapq.nsmallest(k, ((-count, name) for name, count in self.votes.items()))inO(U log k)time per query — negatingcountso higher counts sort first while smaller names still win ties. Ifget_top_k_restaurants(k)is called after almost every vote, maintain all restaurants in a balanced binary search tree keyed by(-count, name): eachvoteremoves(-old_count, name)and inserts(-new_count, name)inO(log U)time, and reading the firstkentries takesO(k)time. - If votes arrived across a fleet of backend servers, how would you keep the global counts accurate and prevent duplicate counting? Partition (shard, meaning split data across servers by a deterministic hash rule) the counters by
restaurant_nameso every vote for"ramen"lands on the exact same shard and updates a single authoritative count. Give each client vote request an idempotency key (a unique request ID stored briefly by the server so network retries are not counted twice), and replicate writes through an ordered log before acknowledging them. Because no restaurant's votes are split across shards, each shard can maintain its own local(winner, max_votes)inO(1), and an aggregator can find the global winner by comparing just the shard winners! - Which data structures would you choose if the catalog grew huge and callers frequently ran range queries by name or by vote total? First clarify whether the range query filters by restaurant name or by vote count. For alphabetical or prefix ranges (such as all restaurants between
"pa"and"pz"), store the counters in a B-tree (a disk-friendly sorted tree that groups keys into blocks so range scans read sequential pages) keyed byrestaurant_name, or a trie (a prefix tree where each path of letters spells out a restaurant name) for fast prefix lookups. For vote-count ranges (such as all restaurants with100to500votes), maintain a secondary B-tree index keyed by(vote_count, restaurant_name)and update a restaurant's entry on each vote inO(log U)time.
Follow-up questions
- How would you adapt the class to support a `get_top_k_restaurants(k)` query returning the top k restaurants in ranked order?
- If votes arrived across a fleet of backend servers, how would you keep the global counts accurate and prevent duplicate counting?
- Which data structures would you choose if the catalog grew huge and callers frequently ran range queries by name or by vote total?
Similar questions
- Predecessor and Successor in Sorted IDs
- Transactional Device Feature CLI Processor
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance