Plurality and Instant-Runoff Vote Counting
Arrays & HashingAuto-graded · 13 test casesLast updated
Tests aggregated vote counting, majority detection, and iterative candidate elimination in ranked-choice systems.
You are implementing two vote-counting methods for an election. Ballots are provided in compressed form: each entry is a list containing a ranking tuple and a count, where the ranking lists candidates from most to least preferred, and the count indicates how many voters submitted that exact preference order.
Implement two functions:
plurality_winner(ballots)
Return the candidate who received the most top-preference votes. If multiple candidates tie for the highest count, return the lexicographically smallest candidate name among those tied.
instant_runoff_winner(ballots)
Count votes using instant-runoff (ranked-choice) rules:
- In each round, tally votes by looking at each ballot and crediting the highest-ranked candidate who has not yet been eliminated.
- If any candidate receives strictly more than 50% of the total votes in that round, that candidate wins immediately.
- Otherwise, eliminate the candidate with the fewest votes in the current round.
- Repeat until a winner emerges or only one candidate remains.
You may assume:
- All ballots rank the same complete set of candidates (no partial rankings).
- No ties occur when determining which candidate to eliminate.
- Candidate names are non-empty strings.
- At least one ballot is provided.
Input format: A list of [ranking, count] pairs, where ranking is a tuple of candidate names and count is a positive integer.
Example:
ballots = [
[("Alice", "Bob", "Carol"), 4],
[("Bob", "Carol", "Alice"), 3],
[("Carol", "Bob", "Alice"), 2]
]
For this input:
plurality_winner(ballots)returns"Alice"(4 top-preference votes vs. 3 for Bob and 2 for Carol).instant_runoff_winner(ballots)returns"Bob":- Round 1: Alice=4, Bob=3, Carol=2 (total 9). No majority. Eliminate Carol.
- Round 2: Alice=4, Bob=5 (Carol's 2 voters now support Bob). Bob has 5 out of 9, which exceeds 50%, so Bob wins.
Constraints
- 1 ≤ number of ballot groups ≤ 1000
- 1 ≤ number of candidates ≤ 50
- 1 ≤ count per ballot group ≤ 10⁶
- All candidate names consist of uppercase and lowercase letters only
- Total vote count fits in a 32-bit integer
Examples
Example 1
Input: plurality_winner([[['A', 'B', 'C'], 4], [['B', 'C', 'A'], 3], [['C', 'B', 'A'], 2]])
Output: 'A'
Hints
Hint 1
For plurality, accumulate first-choice counts in a dictionary, then find the maximum and break ties by name order.
Hint 2
In instant-runoff, track which candidates are still active. Each round, scan ballots and credit the first non-eliminated candidate on each ranking.
Hint 3
Initialize every active candidate's count to zero each round—candidates with no current support must still be eligible for elimination.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Plurality Winner
Count how many times each candidate appears as the top choice across all ballots. Since ballots are compressed with counts, add each ballot's count to the tally for its first-ranked candidate. After processing all ballots, find the maximum vote total, then return the lexicographically smallest candidate name among those achieving that maximum.
Instant-Runoff Winner
Simulate elimination rounds:
- Start with all candidates in a "remaining" set.
- Each round, scan every ballot and credit its count to the first candidate in its ranking who has not been eliminated.
- Initialize every remaining candidate's count to zero at the start of each round (this ensures candidates with no current support are correctly identified for elimination).
- Calculate the total votes cast (sum of all ballot counts).
- If any candidate has strictly more than half the total votes (test with
2 * votes > totalto avoid floating-point issues), that candidate wins immediately. - Otherwise, eliminate the candidate with the fewest votes and repeat.
- If only one candidate remains, return that candidate as the winner.
The key detail: always seed counts to zero for all active candidates. A candidate who appears on ballots but receives no votes in a round must have a count of zero to be correctly identified as the one to eliminate.
Why It Works
Plurality: Each voter contributes exactly once to their top choice. The algorithm faithfully aggregates these contributions, and the tie-breaking rule (smallest name) is deterministic.
Instant-runoff: All ballots rank the full candidate set, so every ballot has a valid active candidate to support in every round. The algorithm mirrors the definition of instant-runoff voting: eliminate the weakest candidate and redistribute their supporters' votes to the next preference, continuing until someone achieves a majority or only one candidate is left. With k candidates, at most k - 1 eliminations occur, guaranteeing termination.
Complexity
Let n be the number of ballot groups and k the number of candidates.
- Plurality winner: O(n) to count votes, then O(k) to find the maximum and resolve ties. Space: O(k).
- Instant-runoff winner: Up to
krounds. Each round processes allnballots, and for each ballot scans up tokcandidates to find the first active one, so each round takes O(n·k). Total time: O(n·k²). Space: O(k) for the remaining set and vote counts.
An optimization: maintain a pointer per ballot tracking the current active candidate, advancing it only when that candidate is eliminated. This amortizes the candidate-scanning cost to O(n·k) across all rounds. The simple version presented here is typically sufficient for interviews.
Edge Cases
- Single candidate: Wins both methods immediately.
- Candidate with zero votes in a round: Must be initialized to 0 and will be eliminated first. Seeding all candidates to zero handles this.
- Exact 50% vote share: Not a majority. The elimination continues. (Though the problem guarantees no elimination ties, the code uses
(votes, name)tuples for deterministic min selection.) - Majority in the first round: Instant-runoff returns immediately without eliminations.
- Plurality tie: Returns the smallest name among tied candidates.
from typing import List
def plurality_winner(ballots: List[List]) -> str:
"""Return candidate with most first-preference votes; break ties by name."""
vote_counts = {}
for ranking, count in ballots:
top_choice = ranking[0]
vote_counts[top_choice] = vote_counts.get(top_choice, 0) + count
max_votes = max(vote_counts.values())
return min(name for name, votes in vote_counts.items() if votes == max_votes)
def instant_runoff_winner(ballots: List[List]) -> str:
"""Return winner via instant-runoff elimination rounds."""
# Collect all candidates
remaining = {candidate for ranking, _ in ballots for candidate in ranking}
while True:
# Base case: only one candidate left
if len(remaining) == 1:
return next(iter(remaining))
# Count votes in this round
vote_counts = {candidate: 0 for candidate in remaining}
total_votes = 0
for ranking, count in ballots:
# Find first candidate still in the race
for candidate in ranking:
if candidate in remaining:
vote_counts[candidate] += count
total_votes += count
break
# Check for majority winner
for candidate, votes in vote_counts.items():
if 2 * votes > total_votes: # Strict majority
return candidate
# No majority: eliminate candidate with fewest votes
weakest = min(vote_counts, key=lambda c: (vote_counts[c], c))
remaining.remove(weakest)