KatInterview

Live Poll Leaderboard: Track the Current Front-Runner

Data Structure DesignAuto-graded · 16 test cases
MediumAuto-gradedData Structure Designhash-mapheapsimulation

Last 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 for operations[i].
    • For "vote", it is a one-element list [name], where name is the venue receiving one more vote.
    • For "get_top_restaurant", it is an empty list [].

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:

  • None for each "vote".
  • For each "get_top_restaurant", the name of the current leader as a string, or None if 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.