InterviewDB Question

Ballot Processing System - OOD Coding Interview

Question Details

Problem

Design a BallotProcessor for a ranked-choice voting election.

python
class BallotProcessor:
    def __init__(self, candidates: list[str]): ...
    def submit_ballot(self, voter_id: str, rankings: list[str]) -> bool:
        # rankings is an ordered list of candidate names (1st choice first)

**Returns** False if voter already submitted or rankings contain invalid names
        ...
    def eliminate(self, candidate: str) -> None:
        # Remove candidate; redistribute their votes to next valid choice
        ...
    def tally(self) -> dict[str, int]:
        # Current first-choice vote count per remaining candidate
        ...
    def winner(self) -> str | None:

**Return** candidate with >50% of current votes, else None
        ...

Example:

bp = BallotProcessor(["A","B","C"])
bp.submit_ballot("v1", ["C","A","B"])
bp.submit_ballot("v2", ["A","B","C"])
bp.submit_ballot("v3", ["C","B","A"])
bp.tally()     -> {"A":1, "B":0, "C":2}
bp.eliminate("B")
bp.tally()     -> {"A":1, "C":2}
bp.winner()    -> "C"  # 2/3 > 50%

Follow-ups
- How do you handle exhausted ballots (all candidates eliminated)?
- What data structure makes vote redistribution O(1) per ballot?
- Extend to return the full elimination round history.

Full Details

Problem

Design a BallotProcessor for a ranked-choice voting election.

python
class BallotProcessor:
    def __init__(self, candidates: list[str]): ...
    def submit_ballot(self, voter_id: str, rankings: list[str]) -> bool:
        # rankings is an ordered list of candidate names (1st choice first)

**Returns** False if voter already submitted or rankings contain invalid names
        ...
    def eliminate(self, candidate: str) -> None:
        # Remove candidate; redistribute their votes to next valid choice
        ...
    def tally(self) -> dict[str, int]:
        # Current first-choice vote count per remaining candidate
        ...
    def winner(self) -> str | None:

**Return** candidate with >50% of current votes, else None
        ...

Example:

bp = BallotProcessor(["A","B","C"])
bp.submit_ballot("v1", ["C","A","B"])
bp.submit_ballot("v2", ["A","B","C"])
bp.submit_ballot("v3", ["C","B","A"])
bp.tally()     -> {"A":1, "B":0, "C":2}
bp.eliminate("B")
bp.tally()     -> {"A":1, "C":2}
bp.winner()    -> "C"  # 2/3 > 50%

Follow-ups
- How do you handle exhausted ballots (all candidates eliminated)?
- What data structure makes vote redistribution O(1) per ballot?
- Extend to return the full elimination round history.

Free preview. Unlock all questions →

Topics

Coding Onsite Phone