Raft Leader Election (Majority)
The heartbeat of the Raft consensus algorithm: a candidate becomes leader only if it wins votes from a strict majority of the cluster. That majority rule is what guarantees at most one leader per term — the property that keeps a distributed system consistent. Decide the outcome of an election round. Solve it in Python or TypeScript, with hidden tests.
The problem
A Raft cluster has n nodes. In an election, a candidate votes for itself and requests votes from the other n-1 peers; you are given grants, a list of booleans (one per peer) saying whether each granted its vote. The candidate becomes leader iff it collects a strict majority — more than half of n, i.e. ⌊n/2⌋ + 1 votes (including its own). Return True if it becomes leader, else False.
n = 5, grants = [True, True, False, False]Truen = 5, grants = [False, False, False, False]Falsen = 4, grants = [True, False, False]False- The candidate always counts its own vote, so total votes = 1 + (number of True in
grants). - Majority means strictly more than half:
⌊n/2⌋ + 1. For evenn, exactly half is not enough. - This strict-majority rule is why two candidates can never both win the same term — any two majorities overlap on at least one node, and a node votes once per term.
Your turn — write it
Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.
Implement election_result(n, grants): count 1 (self) plus the granted votes, and return whether that reaches the majority threshold ⌊n/2⌋ + 1.
- Total votes = 1 (the candidate’s own) + the number of
Trueentries ingrants. - The threshold to win is
n // 2 + 1— a strict majority of the whole cluster, not of those who replied. - Return
total_votes >= threshold. - Note that a single-node cluster (n = 1) always elects its candidate, and an even cluster can suffer a split vote where no one wins.
Explore the topic
See this challenge alongside everything else on the same subject — handbooks, system designs, algorithms and tools, in one place.