Instant-Runoff Voting Winner
Problem statement
An election uses instant-runoff voting. You are given the list of candidates and a list of ballots. Each ballot ranks the candidates from most preferred to least preferred.
The count runs in rounds while more than one candidate is still in the race:
- Each ballot gives one vote to its highest-ranked candidate who is still in the race.
- The candidate with the fewest votes is removed. A candidate with no votes counts as having 0 votes.
- If several candidates tie for the fewest votes, remove the one that appears last in
candidates.
Return the name of the last candidate left.
Interviewer Follow-ups
- Model the candidates as an enum.
- Do not change the ballots while counting.
- How would you scale this to 3 to 15 candidates and millions of ballots stored in a huge file that does not fit in memory?
These follow-ups are for discussion. The tests check only the returned winner.
Function
findRunoffWinner(candidates: String[], ballots: String[][]) → StringExamples
Example 1
candidates = ["Mickey","Donald","Pluto"]ballots = [["Mickey","Donald","Pluto"],["Mickey","Pluto","Donald"],["Donald","Mickey","Pluto"],["Donald","Pluto","Mickey"],["Pluto","Mickey","Donald"]]return = "Mickey"Round 1 counts first choices: Mickey 2, Donald 2, Pluto 1. Pluto has the fewest votes and is removed. Round 2: the ballot that ranked Pluto first now counts for its next choice, Mickey. Mickey has 3 votes and Donald has 2, so Donald is removed. Mickey is the winner.
Example 2
candidates = ["Ann","Bob","Cy"]ballots = [["Ann","Bob","Cy"],["Bob","Ann","Cy"],["Cy","Ann","Bob"],["Cy","Bob","Ann"]]return = "Ann"Round 1: Ann 1, Bob 1, Cy 2. Ann and Bob tie for the fewest votes. Bob is listed later in candidates, so Bob is removed. Round 2: Bob's ballot moves to its next choice, Ann. Ann 2, Cy 2. They tie again, and Cy is listed later, so Cy is removed. Ann wins.
Example 3
candidates = ["Ada","Eve"]ballots = [["Eve","Ada"]]return = "Eve"Ada gets no first-choice votes, which is fewer than Eve's 1 vote, so Ada is removed and Eve wins. A candidate with zero votes still takes part in the count.
Constraints
1 <= candidates.length <= 6- Candidate names are different from each other. Each name is 1 to 8 English letters: an uppercase letter followed by lowercase letters.
1 <= ballots.length <= 500- Every ballot lists every candidate exactly once.