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:
-
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).
- Sum first-choice voter counts (
-
ranked_choice_winner(ballots) -> str- Begin with every candidate active.
- In each round, every voter group contributes its full
voter_countto the earliest candidate in itsrankingwho 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^41 <= C <= 50, whereCis the number of distinct candidates.- Every
rankingis a permutation of the exact sameCnon-empty candidate strings. - Each
voter_countis 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
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
countof voters who cast that exact ranking.Notice one practical detail: callers may pass
ballotsas 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 ballotsWe implement two functions over these pairs:
popular_vote(ballots): return the contender with the highest sum of first-choice voters.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.
Part 1: popular vote over aggregated rows
In
popular_vote, onlyranking[0]matters, and two traps are worth watching out for:- Weight by
count, not by1: a row["Milo", "Nia", "Luna"]withcount = 4represents 4 voters, not 1. - Sum across rows sharing the same
ranking[0]:["Luna", "Milo", "Nia"]: 3and["Luna", "Nia", "Milo"]: 2are 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_placeand 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)- Weight by
Part 2: why we count whole ballot groups instead of individual voters
A naive ranked-choice implementation expands
(ranking, count)intocountseparate copies ofrankingand loops over every individual voter. If10,000,000voters vote across3candidates, there are at most3! = 6distinct rankings—expanding6rows into10,000,000lists turns microsecond work into millions of Python iterations!Every voter who submitted the exact same
rankingfaces the exact sameactiveset in every round, so allcountof them always transfer together to the exact same candidate. Keeping them bundled means each round only scans theBaggregated rows, completely independent of how many millions of voterscountrepresents.Code one ranked-choice round
To tally one round for a given set
activeof remaining candidates:- Initialize every active candidate's tally to
0first. Suppose nobody ranked candidateDfirst (Donly sits in 2nd or 3rd place).Dis still an active candidate with0first-place votes—and unless someone already has> 50%,Dmust be the candidate eliminated in round 1! - Walk down each
rankinguntil the firstname in active, addcounttocounts[name], andbreak. 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- Initialize every active candidate's tally to
Code the elimination loop
Now
ranked_choice_winnercollects all candidates intoactiveand repeats rounds until a winner emerges:- Strict majority check (
2 * votes > total_votes): multiplying by2checksvotes / total_votes > 0.5using exact integers—no floating-point rounding, and exact50%(2 * 3 > 6) rightly evaluates toFalse. - Single survivor check (
len(active) == 1): returns the sole remaining candidate if all others have been eliminated. - Eliminate and recount: remove
_fewest_votes(counts)fromactiveand 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)- Strict majority check (
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]](11voters 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(15voters):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!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):
popular_vote: bundle first choices giveLuna = 3 + 2 = 5,Milo = 4,Nia = 2, so"Luna"wins the popular vote.ranked_choice_winnerRound 1 (active = {Luna, Milo, Nia}): counts areLuna = 5,Milo = 4,Nia = 2(total_votes = 11). Nobody satisfies2 * votes > 11, so the lowest candidate"Nia"(2votes) is removed fromactive.ranked_choice_winnerRound 2 (active = {Luna, Milo}): bundle["Nia", "Milo", "Luna"]: 2skips eliminated"Nia"and lands on"Milo", givingLuna = 5andMilo = 4 + 2 = 6. Now2 * 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_votetime: O(B); space: O(C). We scan allBrows once, adding each row'scounttofirst_place[ranking[0]]inO(1)dictionary time, and then scan at mostmin(B, C)candidate entries once to select the maximum.ranked_choice_winnertime: O(B · C²). InitializingactivereadsBrows ofCcandidates (O(B · C)). Each round either returns a winner or removes one candidate fromactive, so at mostCrounds run. Inside one round,_count_roundscansBrows of up toCnames (O(B · C)withO(1)set lookups intoactive), and picking the majority winner or lowest candidate scansactive(O(C)), givingO(C · (B · C + C)) = O(B · C²)sinceB >= 1.ranked_choice_winnerspace: O(C) (plusO(B)ifballotsis passed as adictand.items()is materialized into a list) to hold theactiveset and per-roundcountsdictionary.
Edge cases
- Multiple rows sharing the same first-place choice:
["Luna", "Milo", "Nia"]: 3and["Luna", "Nia", "Milo"]: 2sum to5for"Luna", beating["Milo", "Nia", "Luna"]: 4. - Candidate with zero first-place votes: a candidate who never appears at
ranking[0]still entersactiveand is initialized to0in_count_round, so they are properly eliminated in round 1 (unless another candidate already exceeds 50%). - Single candidate (
[[["Luna"], 3]]):"Luna"has3of3votes (2 * 3 > 3) and wins immediately in round 1. - Exact 50% share is not a majority:
2 * votes > total_votesrequires 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
dictandList[List]inputs:_ballot_pairshandles both{("Luna", "Milo"): 3}and[[["Luna", "Milo"], 3]]transparently without mutating the caller's structure.
Common mistakes
- Picking the single row with the largest
countinstead of summing byranking[0]: fails whenever a candidate's first-place support is split across different second/third-choice permutations. - Adding
1per 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
countsas votes arrive (counts.get(name, 0) + count): omits 0-vote active candidates fromcounts, causing_fewest_votesto wrongly eliminate someone with positive votes while a 0-vote candidate survives. - Advancing only to
ranking[1]afterranking[0]is eliminated: breaks in later rounds wheneverranking[1]was already eliminated earlier. - Mutating
rankinglists in place (ranking.remove(loser)): corrupts the caller's input data; filtering against a separateactiveset leaves inputs untouched.
Alternative approaches
- Per-row pointer + candidate piles (
O(B · C + C²)): just like unaggregated instant-runoff with piles, store an indexpos[i]for each of theBrows and a bucketrows_for[name]of row indices currently supportingname. Whenloseris eliminated, only advance rows inrows_for[loser]forward untilranking[pos[i]] in active, subtractingcountfromloserand addingcountto the new candidate. Across the whole election eachpos[i]advances at mostCtimes (O(B · C)total), shaving a factor ofCoff theO(B · C²)recount whenCis 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
0votes in that round, shrinkingtotal_votesso the 50% threshold is computed strictly over remaining active votes. Notice_count_roundandtotal_votes = sum(counts.values())already handle partial rankings naturally—you only need to guardif ranking:inpopular_votefor completely empty ballots and returnOptional[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 smallC(sayC <= 8), at most8! = 40,320distinct full rankings exist, which easily fits in memory on a single machine! IfCis large enough thatBitself spans multiple shards, keep rows partitioned across workers: each round, broadcast the tinyactiveset (O(C)), have each worker compute localcounts, sum theO(C)dictionaries on the coordinator, and eliminate the lowest candidate.
Follow-up questions
- What changes are needed if voters are permitted to submit partial rankings rather than ranking every candidate?
- If the no-elimination-tie guarantee is dropped, what deterministic tie-breaking policies are commonly used?
- How would you compute both winners when raw ungrouped ballots are partitioned across a multi-node cluster?
Similar questions
- First-Choice and Instant-Runoff Ballot Tally
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One