Implement Popular and Ranked Voting
CourseraBackend Engineer · Technical ScreenLast updated
This question evaluates algorithmic implementation skills and understanding of voting systems, including aggregation of first-place preferences and the conceptual mechanics of elimination-based ranked-choice counting.
You are given ranked ballots in aggregated form. Each key is an ordered tuple of candidate names representing one voter's preference from highest to lowest, and each value is the number of voters who submitted that exact ranking.
Implement two methods:
popular_vote(ballots) -> candidate
- Return the candidate with the largest number of first-place votes.
ranked_choice_winner(ballots) -> candidate
- In each round, count only the highest-ranked non-eliminated candidate on each ballot.
- If any candidate has more than 50% of the active first-place votes, return that candidate.
- Otherwise, eliminate the candidate with the fewest first-place votes and recount.
- Continue until a candidate has a majority or only one candidate remains.
Assumptions:
- Every ballot ranks the same set of candidates.
- There is no tie when choosing which candidate to eliminate.
Example input:
ballots = {
("A", "B", "C"): 4,
("B", "C", "A"): 3,
("C", "B", "A"): 2
}
For this example:
- The popular-vote winner is
A, becauseAhas the most first-place votes initially. - The ranked-choice winner is
B: first-round counts areA=4, B=3, C=2; eliminateC, thenC's ballots transfer toB, soBbecomes5out of9.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.