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:

  1. vote(restaurant_name: str) -> None: Adds 1 ballot to restaurant_name (starting at 1 the first time that name appears). In voting_system, each "vote" entry has arguments[i] = [restaurant_name] and produces None at index i of the returned list.
  2. 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 has arguments[i] = [] and appends the returned value at index i of the output list.

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,000 distinct restaurant_name values appear across the input.
  • Each restaurant_name is a non-empty string of lowercase ASCII characters.
  • Every entry in operations is either "vote" or "get_top_restaurant".

Step-by-step walkthrough

  1. Understand the problem and tie-breaking rule

    We need to build a live voting counter for restaurants with two operations:

    • vote(restaurant_name): adds 1 vote to restaurant_name (starting at 1 if 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 the Optional[str] return type).

    The judge calls voting_system(operations, arguments) and expects one output per call: None for each "vote" call, and the leading restaurant name (or None) for each "get_top_restaurant" call.

    Pay attention to the scale in the constraints: up to 1,000,000 votes across up to 10,000 unique restaurants, with get_top_restaurant() potentially called after every single vote.

  2. Why recounting on every query is too slow

    A natural first idea is to store a dictionary votes[name] = count so vote is O(1), and then scan the entire dictionary inside get_top_restaurant() to find the best (count, name) pair.

    That works on tiny inputs, but let U be the number of unique restaurants (U <= 10,000) and N be the number of operations (N <= 1,000,000). If get_top_restaurant() runs after every vote, scanning 10,000 entries 1,000,000 times takes roughly 10,000 * 1,000,000 = 10^10 comparisons — 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 in O(1) time.

  3. Key idea: maintain the leader incrementally on each vote

    Ask what actually changes during a single call to vote(restaurant_name):

    1. Exactly one restaurant (restaurant_name) changes its vote count, and that count goes up by 1.
    2. 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_name itself!

    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 winner
    

    Look closely at Case 2 when X is already winner: its new_count becomes M + 1 > M, so Case 2 updates max_votes to M + 1 automatically! Keeping just two extra fields — self.winner and self.max_votes — makes both vote and get_top_restaurant run in O(1) time.

  4. Implement the VotingSystem class

    Let's put the leader comparison in a dedicated helper _should_become_winner so each rule reads like plain English:

    • self.votes maps each restaurant name to its integer vote total.
    • _should_become_winner checks the three winning conditions in order: no winner yet, strictly higher vote count, or tied vote count with a smaller name.
    • get_top_restaurant simply returns self.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.winner
    

    Notice why new_count == self.max_votes and restaurant_name < self.winner is essential: if "diner" votes first (1 vote) and "bistro" votes second (1 vote), "bistro" catches up to a tie rather than exceeding max_votes, and must still take over the lead because "bistro" < "diner".

  5. Wire up the operation runner and trace the tricky cases

    The wrapper function voting_system creates one VotingSystem, loops over (operation, args) pairs, and appends None for "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 results
    

    Let'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"
    
  6. 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 in self.votes, followed by at most one string comparison restaurant_name < self.winner.
  • get_top_restaurant() — O(1) time: We return the stored self.winner attribute directly with zero loops or lookups.
  • Total time across N operations — O(N) average: Each operation performs a constant number of dictionary and variable updates.
  • Space — O(U) for the counter state (plus O(N) for the output list returned by voting_system): self.votes stores one key-value pair per unique restaurant seen so far, while self.winner and self.max_votes take O(1) extra space.

Edge cases

  • Query before any vote is cast: self.winner starts as None, so get_top_restaurant() cleanly returns None.
  • Very first vote: self.winner is None triggers immediately, setting self.winner to that restaurant and self.max_votes to 1.
  • Smaller name catching up later: If "b" reaches 2 votes first and "a" reaches 2 votes later, new_count == self.max_votes and "a" < "b" switches self.winner to "a".
  • Larger name catching up later: If "a" has 1 vote and "z" reaches 1 vote, "z" < "a" is False, so "a" stays on top until "z" reaches 2 votes.
  • Current winner receives another vote: new_count becomes self.max_votes + 1, so new_count > self.max_votes triggers and advances self.max_votes alongside self.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 winner only when new_count > self.max_votes: Forgetting the new_count == self.max_votes and restaurant_name < self.winner branch breaks Example 2, where "diner" votes first and "bistro" ties it afterward.
  • Forgetting to update max_votes when the existing winner gets another vote: If "diner" votes twice (votes["diner"] == 2) while max_votes stays stuck at 1, a single vote for "bistro" falsely looks like a 1 == 1 tie and lets "bistro" steal the lead with fewer votes.
  • Scanning or sorting self.votes inside get_top_restaurant(): Turns an O(1) read into O(U) or O(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 an unvote method 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 update self.votes in vote, and scan self.votes inside get_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 to sortedcontainers.SortedList in 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 top k restaurants 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? If get_top_k_restaurants(k) is called infrequently, keep vote at O(1) and use a min-heap (a binary tree stored in an array that efficiently tracks the k best items) via heapq.nsmallest(k, ((-count, name) for name, count in self.votes.items())) in O(U log k) time per query — negating count so higher counts sort first while smaller names still win ties. If get_top_k_restaurants(k) is called after almost every vote, maintain all restaurants in a balanced binary search tree keyed by (-count, name): each vote removes (-old_count, name) and inserts (-new_count, name) in O(log U) time, and reading the first k entries takes O(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_name so 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) in O(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 by restaurant_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 with 100 to 500 votes), maintain a secondary B-tree index keyed by (vote_count, restaurant_name) and update a restaurant's entry on each vote in O(log U) time.

Follow-up questions

Similar questions

More Ziprecruiter interview questions

All 3 Ziprecruiter questions →