First-Choice and Instant-Runoff Ballot Tally

Hard · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

An election collects ranked voter preferences in ballots, where each element ballots[i] lists unique candidate names ordered from top choice (ballots[i][0]) down to lowest ranked choice. Individual voters do not have to rank every contender—some ballots may omit candidates or be completely empty ([]).

Return a two-key dictionary {"plurality": ..., "runoff": ...} mapping each counting method to the winning candidate's name (or None when zero candidates appear across the entire input):

  1. First-choice plurality ("plurality"):

    • Look only at index 0 of every non-empty ballot.
    • Select the contender with the largest first-choice tally.
    • Break any tie for first place by choosing the lexicographically smallest name (a < b).
  2. Instant-runoff elimination ("runoff"):

    • Initially mark every candidate mentioned anywhere in ballots as active (including contenders with zero top-choice votes).
    • During a round, each ballot assigns one vote to the earliest candidate in its list who is still active. A ballot whose listed candidates have all been eliminated is exhausted and casts zero votes in that round.
    • If a contender wins strictly more than half (> 50%) of the votes cast by non-exhausted ballots in the current round, return that contender immediately.
    • If just one active contender remains, return that contender.
    • Otherwise, remove the active contender with the lowest current-round vote count. Break ties for elimination by removing the lexicographically largest name (a > b).
    • Continue running rounds until a winner emerges.

Examples

Example 1

Input:
ballots = [
  ["Dana", "Eli"],
  ["Dana", "Faye"],
  ["Dana"],
  ["Eli", "Faye"],
  ["Eli", "Dana"],
  ["Faye", "Eli"],
  ["Faye", "Eli"]
]

Output: {"plurality": "Dana", "runoff": "Eli"}

Explanation: - Plurality: Top-choice tallies are Dana = 3, Eli = 2, Faye = 2, so "Dana" wins outright. - Runoff: In Round 1 (7 active ballots), nobody exceeds 3.5 votes. "Eli" and "Faye" tie for last at 2, and the tie-breaker eliminates the lexicographically larger name "Faye". Both ["Faye", "Eli"] ballots move to "Eli", giving Eli = 4 and Dana = 3 in Round 2 (4 / 7 > 50%), so "Eli" wins.

Example 2

Input:
ballots = [
  ["Hana"],
  ["Hana"],
  ["Gabe", "Hana"],
  ["Gabe", "Iris"],
  ["Iris"]
]

Output: {"plurality": "Gabe", "runoff": "Gabe"}

Explanation: - Plurality: "Gabe" and "Hana" tie at 2 top-choice votes (Iris = 1); "Gabe" < "Hana" breaks the tie for "Gabe". - Runoff: Round 1 eliminates "Iris" (1 vote), exhausting ballot ["Iris"] and shrinking the active pool to 4 ballots. Round 2 stands at Gabe = 2, Hana = 2—exact 50% is not a strict majority—so the tie-breaker eliminates "Hana" ("Hana" > "Gabe"), leaving "Gabe" as the sole remaining contender.

Example 3

Input:
ballots = [
  ["Maya", "Kai"],
  ["Maya", "Kai"],
  ["Kai", "Leo"],
  ["Nora", "Leo", "Kai"]
]

Output: {"plurality": "Maya", "runoff": "Kai"}

Explanation: - Plurality: "Maya" leads first choices (Maya = 2, Kai = 1, Nora = 1). - Runoff: "Leo" appears on ballots with 0 top-choice votes and is eliminated in Round 1. Round 2 ties "Kai" and "Nora" at 1 (Maya = 2 of 4, not > 50%), eliminating "Nora"; ballot ["Nora", "Leo", "Kai"] skips already-eliminated "Leo" and lands on "Kai". Round 3 ties "Kai" and "Maya" at 2 of 4, eliminating "Maya" ("Maya" > "Kai"), so "Kai" wins.

Constraints

  • 0 <= len(ballots) <= 10^4
  • Sum of len(b) across all ballots <= 10^5
  • Within any single ballot, all candidate strings are non-empty and pairwise distinct.
  • Notice the opposite tie-break directions: plurality favors the lexicographically smallest string, whereas runoff elimination removes the lexicographically largest string.

Step-by-step walkthrough

  1. Restate the problem and return format

    Each item in ballots ranks unique candidate strings from top choice down to last choice; individual ballots can omit contenders or be empty ([]). We return {"plurality": ..., "runoff": ...} (mapping both keys to None when zero candidates appear anywhere):

    1. "plurality" (first-choice plurality): tally only ballot[0] on each non-empty ballot. Highest count wins; ties go to the lexicographically smallest name (for example "Gabe" < "Hana").
    2. "runoff" (instant-runoff): every contender appearing anywhere in ballots starts active. Each round:
      • Every ballot gives 1 vote to its earliest still-active contender (or 0 votes once all of its listed contenders are gone—an exhausted ballot).
      • Any contender reaching strictly more than 50% of the non-exhausted votes in this round wins immediately.
      • When just one active contender remains, they win.
      • Otherwise, drop the active contender with the lowest tally; ties drop the lexicographically largest name (pointing the opposite way from plurality!).
  2. Part 1: compute the simple plurality winner

    For plurality, second and later choices never matter. We tally ballot[0] for every non-empty ballot into a dictionary, then scan the dictionary keeping the best candidate: strictly more votes always wins, and equal votes pick name < winner.

    def plurality_winner(ballots: List[List[str]]) -> Optional[str]:
        """Return the candidate with the most first-place votes (smallest name breaks ties)."""
        # counts: dict mapping candidate_name -> number of non-empty ballots ranking them first.
        counts: Dict[str, int] = {}
        for ballot in ballots:
            if ballot:
                first_choice = ballot[0]
                counts[first_choice] = counts.get(first_choice, 0) + 1
    
        winner: Optional[str] = None
        for name, votes in counts.items():
            if winner is None:
                winner = name
            else:
                best_votes = counts[winner]
                # Higher vote count wins; ties break toward the lexicographically smallest name.
                if votes > best_votes or (votes == best_votes and name < winner):
                    winner = name
        return winner
    
  3. Part 2: why recounting every ballot from scratch wastes work

    A literal simulation of instant-runoff scans every ballot from index 0 in every single round until it hits a name in active. With k candidates there can be up to k - 1 rounds, so re-scanning total ballot length L each round takes O(k × L) time—scanning past the same eliminated names over and over.

    Two facts let us avoid every redundant scan:

    • Eliminations are permanent: once a candidate leaves active, a ballot never moves backward to an earlier index.
    • Non-losers keep their voters: when loser is eliminated, ballots currently supporting any other candidate do not move at all!
  4. Key idea: ballot piles and forward-only pointers

    Model the count just like election workers sorting paper ballots into physical stacks on candidate tables:

    • pile[name] holds the list of ballot indices [i, ...] currently voting for name, so name's vote count is simply len(pile[name]).
    • position[i] tracks which index inside ballots[i] ballot i currently supports.

    When loser is eliminated, we only pick up pile[loser] and slide each ballot's position[i] forward until it lands on an active candidate (skipping any names eliminated in earlier rounds) or runs off the end:

    Suppose "Leo" was eliminated in an earlier round, and now "Nora" is eliminated:
    
      ballots[i] = ["Nora",  "Leo",  "Kai"]
                      ^        x       ^
                position[i]=0          |
                      |                |
                      +--- skips "Leo" (not in active) ---> lands on "Kai" (position[i]=2)
                                                            moves ballot i into pile["Kai"]
    

    Because position[i] only ever moves right, ballot i takes at most len(ballots[i]) steps across the entire election, making all ballot transfers O(L) total.

  5. Set up the active candidates and initial piles

    Be careful to populate active from every name on every ballot, not just ballot[0]. A candidate ranked second on every ballot starts with 0 votes in round 1 (pile[name] == []) and must be eligible to be eliminated first!

    We also track votes_cast—the count of non-exhausted ballots—so we always measure "more than 50%" against active voters in the current round rather than total initial ballots.

    def runoff_winner(ballots: List[List[str]]) -> Optional[str]:
        """Return the instant-runoff winner, or None if no ballot names any candidate."""
        # Phase 1: collect every candidate mentioned anywhere (including 0-first-choice ones).
        active: Set[str] = set()
        for ballot in ballots:
            for name in ballot:
                active.add(name)
        if not active:
            return None
    
        # pile[name]: list of ballot indices [i, ...] currently contributing a vote to `name`.
        pile: Dict[str, List[int]] = {name: [] for name in active}
        # position[i]: index inside `ballots[i]` of the candidate that ballot i currently supports.
        position = [0] * len(ballots)
        # votes_cast: count of non-exhausted ballots active in the current round.
        votes_cast = 0
    
        for i, ballot in enumerate(ballots):
            if ballot:
                pile[ballot[0]].append(i)
                votes_cast += 1
    
  6. Run the elimination and transfer loop

    In each round:

    1. Check for a strict majority: instead of floating-point votes / votes_cast > 0.5, check 2 * len(pile[name]) > votes_cast. With integers, 2 out of 4 gives 4 > 4 (False), cleanly enforcing strictly more than 50%.
    2. Check if one candidate remains: if len(active) == 1, return that candidate.
    3. Pick the loser: scan active for the smallest len(pile[name]), breaking ties toward name > loser (lexicographically largest).
    4. Redistribute pile.pop(loser): advance each ballot's pointer past eliminated names; if pos == len(ballot), the ballot is exhausted and votes_cast drops by 1.
        # Phase 2: simulate elimination rounds until someone passes 50% or one candidate remains.
        while True:
            for name in active:
                # `2 * votes > votes_cast` checks strictly > 50% using exact integer math.
                if 2 * len(pile[name]) > votes_cast:
                    return name
    
            if len(active) == 1:
                return next(iter(active))
    
            # Find the candidate with the fewest votes; ties eliminate the lexicographically LARGEST name.
            loser: Optional[str] = None
            for name in active:
                votes = len(pile[name])
                if loser is None:
                    loser = name
                else:
                    loser_votes = len(pile[loser])
                    if votes < loser_votes or (votes == loser_votes and name > loser):
                        loser = name
    
            assert loser is not None
            active.remove(loser)
    
            # Phase 3: advance only the eliminated candidate's ballots to their next active choice.
            for i in pile.pop(loser):
                ballot = ballots[i]
                pos = position[i] + 1
                # Skip over any candidates that were already eliminated in earlier rounds.
                while pos < len(ballot) and ballot[pos] not in active:
                    pos += 1
                position[i] = pos
    
                if pos < len(ballot):
                    pile[ballot[pos]].append(i)
                else:
                    # No active candidate remains on this ballot, so it leaves the denominator.
                    votes_cast -= 1
    
  7. Trace Example 1 and Example 3 round by round

    Example 1: [['Dana', 'Eli'], ['Dana', 'Faye'], ['Dana'], ['Eli', 'Faye'], ['Eli', 'Dana'], ['Faye', 'Eli'], ['Faye', 'Eli']]

    Plurality:
      Dana: 3, Eli: 2, Faye: 2  --> unique max is "Dana"
    
    Runoff:
      Round 1 (votes_cast = 7): Dana=3, Eli=2, Faye=2
        2*3 = 6 <= 7 (no majority). Tie for fewest at 2 -> "Faye" > "Eli", so eliminate Faye.
        Both ['Faye', 'Eli'] ballots advance to 'Eli'.
      Round 2 (votes_cast = 7): Eli=4, Dana=3
        2*4 = 8 > 7 -> "Eli" wins!
    

    Example 3 (0-vote contender + skipping eliminated choice): [['Maya', 'Kai'], ['Maya', 'Kai'], ['Kai', 'Leo'], ['Nora', 'Leo', 'Kai']]

    Plurality:
      Maya: 2, Kai: 1, Nora: 1  --> "Maya"
    
    Runoff:
      Round 1 (votes_cast = 4): Maya=2, Kai=1, Nora=1, Leo=0
        2*2 = 4 <= 4 (exact 50% is NOT > 50%). Fewest is Leo (0) -> eliminate Leo!
      Round 2 (votes_cast = 4): Maya=2, Kai=1, Nora=1
        Tie for fewest at 1 -> largest name "Nora" > "Kai", so eliminate Nora!
        ['Nora', 'Leo', 'Kai'] skips already-eliminated Leo -> lands on Kai.
      Round 3 (votes_cast = 4): Maya=2, Kai=2
        Tie at 2 -> largest name "Maya" > "Kai", so eliminate Maya!
        Both ['Maya', 'Kai'] ballots advance to Kai.
      Round 4 (votes_cast = 4): Kai=4
        2*4 = 8 > 4 -> "Kai" wins!
    
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def plurality_winner(ballots: List[List[str]]) -> Optional[str]:
        """Return the candidate with the most first-place votes (smallest name breaks ties)."""
        # counts: dict mapping candidate_name -> number of non-empty ballots ranking them first.
        counts: Dict[str, int] = {}
        for ballot in ballots:
            if ballot:
                first_choice = ballot[0]
                counts[first_choice] = counts.get(first_choice, 0) + 1
    
        winner: Optional[str] = None
        for name, votes in counts.items():
            if winner is None:
                winner = name
            else:
                best_votes = counts[winner]
                # Higher vote count wins; ties break toward the lexicographically smallest name.
                if votes > best_votes or (votes == best_votes and name < winner):
                    winner = name
        return winner
    
    
    def runoff_winner(ballots: List[List[str]]) -> Optional[str]:
        """Return the instant-runoff winner, or None if no ballot names any candidate."""
        # Phase 1: collect every candidate mentioned anywhere (including 0-first-choice ones).
        active: Set[str] = set()
        for ballot in ballots:
            for name in ballot:
                active.add(name)
        if not active:
            return None
    
        # pile[name]: list of ballot indices [i, ...] currently contributing a vote to `name`.
        pile: Dict[str, List[int]] = {name: [] for name in active}
        # position[i]: index inside `ballots[i]` of the candidate that ballot i currently supports.
        position = [0] * len(ballots)
        # votes_cast: count of non-exhausted ballots active in the current round.
        votes_cast = 0
    
        for i, ballot in enumerate(ballots):
            if ballot:
                pile[ballot[0]].append(i)
                votes_cast += 1
    
        # Phase 2: simulate elimination rounds until someone passes 50% or one candidate remains.
        while True:
            for name in active:
                # `2 * votes > votes_cast` checks strictly > 50% using exact integer math.
                if 2 * len(pile[name]) > votes_cast:
                    return name
    
            if len(active) == 1:
                return next(iter(active))
    
            # Find the candidate with the fewest votes; ties eliminate the lexicographically LARGEST name.
            loser: Optional[str] = None
            for name in active:
                votes = len(pile[name])
                if loser is None:
                    loser = name
                else:
                    loser_votes = len(pile[loser])
                    if votes < loser_votes or (votes == loser_votes and name > loser):
                        loser = name
    
            assert loser is not None
            active.remove(loser)
    
            # Phase 3: advance only the eliminated candidate's ballots to their next active choice.
            for i in pile.pop(loser):
                ballot = ballots[i]
                pos = position[i] + 1
                # Skip over any candidates that were already eliminated in earlier rounds.
                while pos < len(ballot) and ballot[pos] not in active:
                    pos += 1
                position[i] = pos
    
                if pos < len(ballot):
                    pile[ballot[pos]].append(i)
                else:
                    # No active candidate remains on this ballot, so it leaves the denominator.
                    votes_cast -= 1
    
    
    def plurality_and_runoff(ballots: List[List[str]]) -> Dict[str, Optional[str]]:
        return {
            "plurality": plurality_winner(ballots),
            "runoff": runoff_winner(ballots),
        }
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture counting a paper election by placing one tray on a table for each candidate. For plurality voting (a single-round rule where only each voter's first choice counts), you sort every non-empty ballot into the tray of its top choice and pick the fullest tray. For instant-runoff voting (a multi-round system that repeatedly eliminates the last-place candidate and transfers their ballots to each voter's next remaining preference), you clip a small marker (position[i]) onto each ballot showing which candidate tray it currently sits in. Whenever nobody holds more than half of the active ballots, you close the tray with the fewest ballots, pick up only that tray's stack, and slide each ballot's clip forward past any closed trays until it lands on an open tray—or set the ballot aside if every candidate on it has been eliminated.

Why not just re-read every ballot from the top at the start of every round? If 10,000 voters each rank 200 candidates, there can be 199 elimination rounds, and re-scanning every ballot from index 0 each round repeats up to 199 × 2,000,000 lookups over candidates who were eliminated long ago. Because an eliminated candidate never re-enters the race, a ballot's clip only ever moves forward, so keeping trays (pile) plus per-ballot pointers (position) touches each name on each ballot at most once across the entire election.

Walk through Example 1 ([Dana, Eli], [Dana, Faye], [Dana], [Eli, Faye], [Eli, Dana], [Faye, Eli], [Faye, Eli]):

  1. Plurality: first choices give Dana = 3, Eli = 2, Faye = 2, so "Dana" wins plurality (and if two leaders tied, lexicographical order—standard dictionary character-by-character order—would pick the smaller string).
  2. Runoff Round 1 (votes_cast = 7): trays hold Dana: 3, Eli: 2, Faye: 2. Nobody has strictly more than 3.5 votes (2 * votes > 7 is false for all three). "Eli" and "Faye" tie for fewest at 2, and "Faye" > "Eli" eliminates "Faye", sliding both [Faye, Eli] pointers to Eli.
  3. Runoff Round 2 (votes_cast = 7): trays now hold Eli: 4, Dana: 3. Since 2 * 4 = 8 > 7, "Eli" has a strict majority and wins the runoff.

Complexity

Let n be the number of ballots, L be the sum of lengths of all ballots, and k be the number of distinct candidates (k <= L), assuming candidate names have O(1) bounded length.

  • Plurality time: O(n + k); space: O(k). We inspect at most the first entry of each of the n ballots in O(1) dictionary time, then scan at most k candidate counts once to pick the winner.
  • Runoff time: O(n + L + k²). Gathering active candidates and placing initial ballots takes O(n + L). Each round either finds a winner or eliminates one candidate, so there are at most k rounds, and each round scans the active candidates (at most k of them) to check majority and pick the loser, costing O(k²) total. Advancing position[i] across all rounds takes O(L) total by amortized analysis (accounting for total work across all steps rather than worst-case per step): each ballot's pointer only moves right, so it advances at most len(ballot) times over the whole run.
  • Runoff space: O(n + k). Every ballot index sits in at most one candidate's pile (O(n) total across k lists), position has length n, and active holds at most k candidate names.

Edge cases

  • Empty input ([]) or only empty ballots ([[], []]): active and counts are both empty, so both functions cleanly return None.
  • Mix of empty and non-empty ballots: empty ballots are skipped during initialization and never inflate votes_cast.
  • Exact 50% tie (2 out of 4 votes): the rule requires strictly more than 50%; 2 * 2 > 4 evaluates to False, triggering an elimination instead of a premature win.
  • Exhausted ballots shrinking the majority threshold: an exhausted ballot (a partial ballot whose listed candidates have all been eliminated) decrements votes_cast by 1, so 50% is always measured against ballots still casting a vote in the current round.
  • Skipping multiple eliminated candidates in one transfer: if ballot ["D", "C", "B", "Z"] loses "D" after "C" and "B" were already eliminated earlier, the while loop skips straight to "Z".
  • Candidate with zero first-choice votes: a candidate who only appears in 2nd or 3rd place still starts in active with an empty pile (0 votes) and is eliminated before any candidate with >= 1 vote.

Common mistakes

  • Using >= instead of > for the 50% check: votes >= total / 2 wrongly hands a win to a candidate with exactly half the votes (such as 2 out of 4), skipping required runoff transfers.
  • Dividing by len(ballots) instead of votes_cast: when partial ballots exhaust, the active pool shrinks; dividing by total original ballots can prevent any remaining candidate from ever crossing 50% of len(ballots).
  • Reversing one of the tie-breakers: plurality picks the lexicographically smallest name (name < winner), whereas runoff elimination removes the lexicographically largest name (name > loser).
  • Writing min(active, key=lambda c: len(pile[c])): breaks ties arbitrarily by set iteration order instead of choosing the lexicographically largest tied name.
  • Initializing active from ballot[0] only: leaves 0-first-choice candidates out of round 1, which changes who gets eliminated first (and fails to break ties properly if all first-choice candidates are eliminated).
  • Advancing a transferred ballot by just + 1 without a while loop: hands the ballot to an already-eliminated candidate instead of continuing down the voter's ranking.

Alternative approaches

  • Full recount each round (O(k × L)): scan every ballot from index 0 in each round until finding the first name in active. Much shorter to write (and great as a brute-force test oracle), at the cost of repeating scans over long ballots across many rounds.
  • Lazy heaps for leader and loser (O((n + L) log(k + L))): because an active candidate's pile only grows when transfers arrive, you can push updated (votes, tie_key, name) entries into min/max heaps and discard stale entries upon popping, replacing the O(k²) active-set scans when k is huge and ballots are short.

Follow-up questions

  • How would you extend the simulation to emit a structured round-by-round tally and transfer report? At the start of each round, append a snapshot containing {name: len(pile[name]) for name in sorted(active)}, votes_cast, and exhausted_count, plus the eliminated loser and a transfer map recording how many of loser's ballots moved to each active candidate (or exhausted). Recording this adds O(k) work per round, keeping the overall O(n + L + k²) runtime unchanged.
  • How should the implementation sanitize ballots if voters can accidentally list duplicate names or ineligible write-ins? Add a single O(L) sanitization pass before counting that filters each ballot against a valid_candidates set while deduplicating per ballot with a seen set (preserving first occurrence order, e.g., ["Dana", "Dana", "Eli"] -> ["Dana", "Eli"]). That keeps both plurality_winner and runoff_winner simple and guarantees a ballot never counts twice or skips improperly.
  • When is it mathematically safe to eliminate multiple trailing candidates at once in a single round? If you sort active candidates by vote count ascending, any prefix of lowest candidates whose combined votes are strictly less than the next candidate's current votes can be eliminated together in one batch without changing the winner (assuming no tie sits at the boundary). Even if all of their ballots transferred to a single member of that prefix, that candidate could still never catch the candidate above them.

Follow-up questions

Similar questions

More Coursera interview questions

All 2 Coursera questions →