Popular and Ranked-Choice Winners on Grouped Ballots

Hard · Coding & Algorithms · Backend Engineer · Technical Screen

Problem Statement

Instead of receiving one record per individual voter, an election service receives grouped ranked ballots. Each entry pairs an ordered preference list of candidate names (from favorite at index 0 to least favorite at the end) with the positive integer count of voters who submitted that exact ranking. Callers may supply ballots either as a list of [ranking, voter_count] pairs or as a dictionary {ranking_tuple: voter_count}.

Implement two functions over ballots:

  1. popular_vote(ballots) -> str

    • Sum first-choice voter counts (ranking[0]) across all grouped entries and return the contender with the highest total (if tied for top, any tied leader—such as the lexicographically smallest name—is valid).
  2. ranked_choice_winner(ballots) -> str

    • Begin with every candidate active.
    • In each round, every voter group contributes its full voter_count to the earliest candidate in its ranking who is still active.
    • If any active candidate receives strictly more than 50% of total votes in that round, return that candidate immediately.
    • If only one active candidate remains, return that candidate.
    • Otherwise, eliminate the active candidate with the lowest round total and start the next round.

Every ranking lists the exact same set of candidates, and whenever an elimination is needed in ranked_choice_winner, there is a single unique lowest-scoring candidate (no tie for last place).

Examples

Example 1

Input:
ballots = [
  [["Luna", "Milo", "Nia"], 3],
  [["Luna", "Nia", "Milo"], 2],
  [["Milo", "Nia", "Luna"], 4],
  [["Nia", "Milo", "Luna"], 2]
]

Output:
popular_vote(ballots)         -> "Luna"
ranked_choice_winner(ballots) -> "Milo"

Explanation: - popular_vote: Combining both "Luna"-first groups gives Luna = 3 + 2 = 5, ahead of Milo = 4 and Nia = 2, so "Luna" wins the popular tally. - ranked_choice_winner: Across 11 total voters, Round 1 gives Luna = 5, Milo = 4, Nia = 2 (nobody exceeds 5.5). "Nia" has the fewest votes and is eliminated; her 2 voters move to their next active choice "Milo", lifting "Milo" to 6 out of 11 (> 50%) in Round 2.

Example 2

Input:
ballots = [
  [["Omar", "Pia", "Quinn", "Rory"], 6],
  [["Pia", "Quinn", "Omar", "Rory"], 4],
  [["Quinn", "Pia", "Omar", "Rory"], 3],
  [["Rory", "Quinn", "Pia", "Omar"], 2]
]

Output:
popular_vote(ballots)         -> "Omar"
ranked_choice_winner(ballots) -> "Quinn"

Explanation: - popular_vote: First-choice totals are Omar = 6, Pia = 4, Quinn = 3, Rory = 2, so "Omar" leads. - ranked_choice_winner: Out of 15 voters, Round 1 eliminates "Rory" (2 votes). Those 2 votes transfer to "Quinn", making Round 2 totals Omar = 6, Quinn = 5, Pia = 4—now "Pia" is lowest and is eliminated next. "Pia"'s 4 voters move to "Quinn", giving Quinn = 9 out of 15 (> 50%) in Round 3.

Constraints

  • 1 <= len(ballots) <= 10^4
  • 1 <= C <= 50, where C is the number of distinct candidates.
  • Every ranking is a permutation of the exact same C non-empty candidate strings.
  • Each voter_count is a positive integer (1 <= voter_count <= 10^9).
  • No tie occurs when selecting the lowest-vote candidate to eliminate in ranked_choice_winner.

Step-by-step walkthrough

  1. Restate the problem and input shapes

    Instead of one ballot per voter, ballots arrive aggregated by ranking: each entry pairs an ordered ranking of candidates (favorite first) with the integer count of voters who cast that exact ranking.

    Notice one practical detail: callers may pass ballots as a dictionary {("Luna", "Milo", "Nia"): 3, ...} or as JSON-friendly [ranking, count] pairs such as [[["Luna", "Milo", "Nia"], 3], ...]. A tiny helper normalizes both into (ranking, count) pairs so both functions work seamlessly with either format:

    def _ballot_pairs(ballots) -> List:
        """Normalize input into (ranking, voter_count) pairs for either dict or list input."""
        # Callers may pass `{('Luna', 'Milo', 'Nia'): 3}` or `[[['Luna', 'Milo', 'Nia'], 3]]`.
        if isinstance(ballots, dict):
            return list(ballots.items())
        return ballots
    

    We implement two functions over these pairs:

    1. popular_vote(ballots): return the contender with the highest sum of first-choice voters.
    2. ranked_choice_winner(ballots): run instant-runoff rounds—crediting each group's voters to its earliest remaining contender—returning as soon as someone holds strictly more than 50% of the active votes (or is the sole remaining contender), and otherwise removing the unique lowest-vote contender.
  2. Part 1: popular vote over aggregated rows

    In popular_vote, only ranking[0] matters, and two traps are worth watching out for:

    • Weight by count, not by 1: a row ["Milo", "Nia", "Luna"] with count = 4 represents 4 voters, not 1.
    • Sum across rows sharing the same ranking[0]: ["Luna", "Milo", "Nia"]: 3 and ["Luna", "Nia", "Milo"]: 2 are different full rankings, yet both give first-place votes to "Luna":
    Row 1:  ["Luna", "Milo", "Nia"], count = 3  --> +3 for Luna
    Row 2:  ["Luna", "Nia", "Milo"], count = 2  --> +2 for Luna   (Luna total = 5)
    Row 3:  ["Milo", "Nia", "Luna"], count = 4  --> +4 for Milo   (Milo total = 4)
                                                     Winner: Luna (even though Row 3 is the single largest row!)
    

    We accumulate totals in first_place and pick the maximum in one pass (breaking any first-place tie alphabetically so the output is deterministic):

    def _most_votes(counts: Dict[str, int]) -> str:
        """Return the candidate with the largest vote count (alphabetically smallest breaks ties)."""
        best_name: Optional[str] = None
        for name, votes in counts.items():
            if best_name is None:
                best_name = name
            else:
                best_votes = counts[best_name]
                if votes > best_votes or (votes == best_votes and name < best_name):
                    best_name = name
        assert best_name is not None
        return best_name
    
    
    def popular_vote(ballots: List[List]) -> str:
        # first_place: dict mapping candidate_name -> total first-choice voters across all rows.
        first_place: Dict[str, int] = {}
        for ranking, count in _ballot_pairs(ballots):
            top_choice = ranking[0]
            # Sum `count` (not 1), because several distinct rankings can share the same first choice.
            first_place[top_choice] = first_place.get(top_choice, 0) + count
        return _most_votes(first_place)
    
  3. Part 2: why we count whole ballot groups instead of individual voters

    A naive ranked-choice implementation expands (ranking, count) into count separate copies of ranking and loops over every individual voter. If 10,000,000 voters vote across 3 candidates, there are at most 3! = 6 distinct rankings—expanding 6 rows into 10,000,000 lists turns microsecond work into millions of Python iterations!

    Every voter who submitted the exact same ranking faces the exact same active set in every round, so all count of them always transfer together to the exact same candidate. Keeping them bundled means each round only scans the B aggregated rows, completely independent of how many millions of voters count represents.

  4. Code one ranked-choice round

    To tally one round for a given set active of remaining candidates:

    1. Initialize every active candidate's tally to 0 first. Suppose nobody ranked candidate D first (D only sits in 2nd or 3rd place). D is still an active candidate with 0 first-place votes—and unless someone already has > 50%, D must be the candidate eliminated in round 1!
    2. Walk down each ranking until the first name in active, add count to counts[name], and break. Walking with a loop automatically skips over one, two, or more already-eliminated candidates.
    def _count_round(pairs: List, active: Set[str]) -> Dict[str, int]:
        """Tally one instant-runoff round: each ballot group backs its top still-active candidate."""
        # Initialize every active candidate to 0 so 0-vote candidates are not overlooked during elimination.
        counts: Dict[str, int] = {name: 0 for name in active}
        for ranking, count in pairs:
            for name in ranking:
                if name in active:
                    # Every voter in this group shares the exact same first remaining choice.
                    counts[name] += count
                    break
        return counts
    
  5. Code the elimination loop

    Now ranked_choice_winner collects all candidates into active and repeats rounds until a winner emerges:

    • Strict majority check (2 * votes > total_votes): multiplying by 2 checks votes / total_votes > 0.5 using exact integers—no floating-point rounding, and exact 50% (2 * 3 > 6) rightly evaluates to False.
    • Single survivor check (len(active) == 1): returns the sole remaining candidate if all others have been eliminated.
    • Eliminate and recount: remove _fewest_votes(counts) from active and recount in the next iteration.
    def _fewest_votes(counts: Dict[str, int]) -> str:
        """Return the active candidate with the smallest vote count."""
        # The problem guarantees no tie for fewest votes; `name < worst_name` keeps ties deterministic.
        worst_name: Optional[str] = None
        for name, votes in counts.items():
            if worst_name is None:
                worst_name = name
            else:
                worst_votes = counts[worst_name]
                if votes < worst_votes or (votes == worst_votes and name < worst_name):
                    worst_name = name
        assert worst_name is not None
        return worst_name
    
    
    def ranked_choice_winner(ballots: List[List]) -> str:
        pairs = _ballot_pairs(ballots)
    
        # Phase 1: gather all candidates appearing in the rankings.
        active: Set[str] = set()
        for ranking, _ in pairs:
            for name in ranking:
                active.add(name)
    
        # Phase 2: recount, test for > 50% majority, or eliminate the lowest candidate and repeat.
        while True:
            counts = _count_round(pairs, active)
            total_votes = sum(counts.values())
    
            for name, votes in counts.items():
                # `2 * votes > total_votes` tests strictly > 50% in exact integer arithmetic.
                if 2 * votes > total_votes:
                    return name
    
            if len(active) == 1:
                return next(iter(active))
    
            loser = _fewest_votes(counts)
            active.remove(loser)
    
  6. Trace Example 1 and Example 2 round by round

    Example 1: [[["Luna", "Milo", "Nia"], 3], [["Luna", "Nia", "Milo"], 2], [["Milo", "Nia", "Luna"], 4], [["Nia", "Milo", "Luna"], 2]] (11 voters total)

    popular_vote:
      Luna: 3 + 2 = 5, Milo: 4, Nia: 2  --> "Luna"
    
    ranked_choice_winner:
      Round 1  active = {Luna, Milo, Nia}
               Luna=5, Milo=4, Nia=2 (total 11; 2*5 = 10 <= 11, no majority)
               Fewest is Nia (2) -> eliminate Nia
      Round 2  active = {Luna, Milo}
               ["Luna","Milo","Nia"]:3 -> Luna (+3)
               ["Luna","Nia","Milo"]:2 -> Luna (+2)
               ["Milo","Nia","Luna"]:4 -> Milo (+4)
               ["Nia","Milo","Luna"]:2 -> skips Nia, hits Milo (+2)
               Luna=5, Milo=6 (total 11; 2*6 = 12 > 11) -> "Milo" wins!
    

    Example 2 (why we must recount before picking the next loser): [Omar,Pia,Quinn,Rory]: 6, [Pia,Quinn,Omar,Rory]: 4, [Quinn,Pia,Omar,Rory]: 3, [Rory,Quinn,Pia,Omar]: 2 (15 voters):

      Round 1: Omar=6, Pia=4, Quinn=3, Rory=2  -> eliminate Rory (2)
      Round 2: Rory's 2 votes move to Quinn -> Omar=6, Quinn=5, Pia=4  -> now Pia (4) is lowest, NOT Quinn!
               eliminate Pia (4)
      Round 3: Pia's 4 votes move to Quinn -> Quinn=9, Omar=6 (2*9 > 15) -> "Quinn" wins!
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def _ballot_pairs(ballots) -> List:
        """Normalize input into (ranking, voter_count) pairs for either dict or list input."""
        # Callers may pass `{('Luna', 'Milo', 'Nia'): 3}` or `[[['Luna', 'Milo', 'Nia'], 3]]`.
        if isinstance(ballots, dict):
            return list(ballots.items())
        return ballots
    
    
    def _most_votes(counts: Dict[str, int]) -> str:
        """Return the candidate with the largest vote count (alphabetically smallest breaks ties)."""
        best_name: Optional[str] = None
        for name, votes in counts.items():
            if best_name is None:
                best_name = name
            else:
                best_votes = counts[best_name]
                if votes > best_votes or (votes == best_votes and name < best_name):
                    best_name = name
        assert best_name is not None
        return best_name
    
    
    def _fewest_votes(counts: Dict[str, int]) -> str:
        """Return the active candidate with the smallest vote count."""
        # The problem guarantees no tie for fewest votes; `name < worst_name` keeps ties deterministic.
        worst_name: Optional[str] = None
        for name, votes in counts.items():
            if worst_name is None:
                worst_name = name
            else:
                worst_votes = counts[worst_name]
                if votes < worst_votes or (votes == worst_votes and name < worst_name):
                    worst_name = name
        assert worst_name is not None
        return worst_name
    
    
    def popular_vote(ballots: List[List]) -> str:
        # first_place: dict mapping candidate_name -> total first-choice voters across all rows.
        first_place: Dict[str, int] = {}
        for ranking, count in _ballot_pairs(ballots):
            top_choice = ranking[0]
            # Sum `count` (not 1), because several distinct rankings can share the same first choice.
            first_place[top_choice] = first_place.get(top_choice, 0) + count
        return _most_votes(first_place)
    
    
    def _count_round(pairs: List, active: Set[str]) -> Dict[str, int]:
        """Tally one instant-runoff round: each ballot group backs its top still-active candidate."""
        # Initialize every active candidate to 0 so 0-vote candidates are not overlooked during elimination.
        counts: Dict[str, int] = {name: 0 for name in active}
        for ranking, count in pairs:
            for name in ranking:
                if name in active:
                    # Every voter in this group shares the exact same first remaining choice.
                    counts[name] += count
                    break
        return counts
    
    
    def ranked_choice_winner(ballots: List[List]) -> str:
        pairs = _ballot_pairs(ballots)
    
        # Phase 1: gather all candidates appearing in the rankings.
        active: Set[str] = set()
        for ranking, _ in pairs:
            for name in ranking:
                active.add(name)
    
        # Phase 2: recount, test for > 50% majority, or eliminate the lowest candidate and repeat.
        while True:
            counts = _count_round(pairs, active)
            total_votes = sum(counts.values())
    
            for name, votes in counts.items():
                # `2 * votes > total_votes` tests strictly > 50% in exact integer arithmetic.
                if 2 * votes > total_votes:
                    return name
    
            if len(active) == 1:
                return next(iter(active))
    
            loser = _fewest_votes(counts)
            active.remove(loser)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of the input as neatly bundled stacks of identical paper ballots, where each bundle carries a sticky note stating how many voters cast that exact preference order (for example, ["Luna", "Milo", "Nia"], 3 is a bundle of 3 identical ballots). Because every ballot inside one bundle lists candidates in the exact same order, those voters always move as a single block in every round: you never need to unbundle them into individual voters. For popular vote (first-past-the-post, where only first choices count), you add up the bundle sizes for each first-place candidate. For ranked-choice voting (also called instant-runoff voting, where the lowest-scoring candidate is eliminated round by round until someone exceeds 50%), you maintain a set active of remaining candidates and let each bundle add its entire count to the first candidate in its ranking that is still in active.

Why not expand each (ranking, count) bundle into count separate voter lists, or just eliminate candidates in increasing order of their round-1 totals? Expanding bundles makes runtime proportional to total voters—so 50 million voters across 6 distinct rankings would do 50 million operations instead of 6! And fixing the elimination order from round 1 is wrong because transferred votes from the last-place candidate can lift the second-lowest candidate past a rival who started ahead of them.

Walk through [[["Luna", "Milo", "Nia"], 3], [["Luna", "Nia", "Milo"], 2], [["Milo", "Nia", "Luna"], 4], [["Nia", "Milo", "Luna"], 2]] (11 voters total):

  1. popular_vote: bundle first choices give Luna = 3 + 2 = 5, Milo = 4, Nia = 2, so "Luna" wins the popular vote.
  2. ranked_choice_winner Round 1 (active = {Luna, Milo, Nia}): counts are Luna = 5, Milo = 4, Nia = 2 (total_votes = 11). Nobody satisfies 2 * votes > 11, so the lowest candidate "Nia" (2 votes) is removed from active.
  3. ranked_choice_winner Round 2 (active = {Luna, Milo}): bundle ["Nia", "Milo", "Luna"]: 2 skips eliminated "Nia" and lands on "Milo", giving Luna = 5 and Milo = 4 + 2 = 6. Now 2 * 6 = 12 > 11, so "Milo" has a strict majority and wins.

Complexity

Let B be the number of aggregated ballot rows (distinct rankings) and C be the number of candidates, assuming candidate names have O(1) bounded length. Notice that the total number of individual voters V does not appear in the complexity at all—only integer addition on count is performed.

  • popular_vote time: O(B); space: O(C). We scan all B rows once, adding each row's count to first_place[ranking[0]] in O(1) dictionary time, and then scan at most min(B, C) candidate entries once to select the maximum.
  • ranked_choice_winner time: O(B · C²). Initializing active reads B rows of C candidates (O(B · C)). Each round either returns a winner or removes one candidate from active, so at most C rounds run. Inside one round, _count_round scans B rows of up to C names (O(B · C) with O(1) set lookups into active), and picking the majority winner or lowest candidate scans active (O(C)), giving O(C · (B · C + C)) = O(B · C²) since B >= 1.
  • ranked_choice_winner space: O(C) (plus O(B) if ballots is passed as a dict and .items() is materialized into a list) to hold the active set and per-round counts dictionary.

Edge cases

  • Multiple rows sharing the same first-place choice: ["Luna", "Milo", "Nia"]: 3 and ["Luna", "Nia", "Milo"]: 2 sum to 5 for "Luna", beating ["Milo", "Nia", "Luna"]: 4.
  • Candidate with zero first-place votes: a candidate who never appears at ranking[0] still enters active and is initialized to 0 in _count_round, so they are properly eliminated in round 1 (unless another candidate already exceeds 50%).
  • Single candidate ([[["Luna"], 3]]): "Luna" has 3 of 3 votes (2 * 3 > 3) and wins immediately in round 1.
  • Exact 50% share is not a majority: 2 * votes > total_votes requires strictly more than half, avoiding floating-point precision glitches and rejecting a 50% tie.
  • Skipping multiple eliminated candidates: if both "Rory" and "Pia" have been eliminated, scanning ["Rory", "Pia", "Quinn", "Omar"] skips "Rory" and "Pia" in turn and credits "Quinn".
  • Both dict and List[List] inputs: _ballot_pairs handles both {("Luna", "Milo"): 3} and [[["Luna", "Milo"], 3]] transparently without mutating the caller's structure.

Common mistakes

  • Picking the single row with the largest count instead of summing by ranking[0]: fails whenever a candidate's first-place support is split across different second/third-choice permutations.
  • Adding 1 per row instead of + count: counts distinct ranking patterns rather than voters.
  • Pre-sorting candidates by round-1 votes and eliminating in that fixed order: misses overtakes where transferred votes boost a trailing candidate ahead of someone above them.
  • Only initializes counts as votes arrive (counts.get(name, 0) + count): omits 0-vote active candidates from counts, causing _fewest_votes to wrongly eliminate someone with positive votes while a 0-vote candidate survives.
  • Advancing only to ranking[1] after ranking[0] is eliminated: breaks in later rounds whenever ranking[1] was already eliminated earlier.
  • Mutating ranking lists in place (ranking.remove(loser)): corrupts the caller's input data; filtering against a separate active set leaves inputs untouched.

Alternative approaches

  • Per-row pointer + candidate piles (O(B · C + C²)): just like unaggregated instant-runoff with piles, store an index pos[i] for each of the B rows and a bucket rows_for[name] of row indices currently supporting name. When loser is eliminated, only advance rows in rows_for[loser] forward until ranking[pos[i]] in active, subtracting count from loser and adding count to the new candidate. Across the whole election each pos[i] advances at most C times (O(B · C) total), shaving a factor of C off the O(B · C²) recount when C is large.

Follow-up questions

  • What changes are needed if voters are permitted to submit partial rankings rather than ranking every candidate? A row whose listed candidates have all been eliminated becomes an exhausted ballot (a ballot with no active preferences left) and contributes 0 votes in that round, shrinking total_votes so the 50% threshold is computed strictly over remaining active votes. Notice _count_round and total_votes = sum(counts.values()) already handle partial rankings naturally—you only need to guard if ranking: in popular_vote for completely empty ballots and return Optional[str] if all ballots exhaust.
  • If the no-elimination-tie guarantee is dropped, what deterministic tie-breaking policies are commonly used? Election rules must fix a deterministic tie-breaking rule (a pre-agreed rule for choosing one candidate when counts are equal) ahead of time because eliminating different tied candidates can change the final winner. Common choices include eliminating whichever tied candidate had fewer votes in the earliest prior round where they differed, batch-eliminating all tied bottom candidates when their combined votes cannot overtake the next candidate up, or using a lexicographical / seeded random tie-breaker.
  • How would you compute both winners when raw ungrouped ballots are partitioned across a multi-node cluster? Run a MapReduce / Spark GROUP BY ranking COUNT(*) aggregation first to collapse billions of individual ballots into (ranking, count) pairs—with small C (say C <= 8), at most 8! = 40,320 distinct full rankings exist, which easily fits in memory on a single machine! If C is large enough that B itself spans multiple shards, keep rows partitioned across workers: each round, broadcast the tiny active set (O(C)), have each worker compute local counts, sum the O(C) dictionaries on the coordinator, and eliminate the lowest candidate.

Follow-up questions

Similar questions

More Coursera interview questions

All 2 Coursera questions →