CODING CHALLENGE · N°49

Raft Leader Election (Majority)

Easy Distributed SystemsConsensusRaft

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.

EXAMPLE 1
Input n = 5, grants = [True, True, False, False]
Output True
1 self + 2 = 3 votes; majority of 5 is 3
EXAMPLE 2
Input n = 5, grants = [False, False, False, False]
Output False
only its own vote — far short of 3
EXAMPLE 3
Input n = 4, grants = [True, False, False]
Output False
2 votes, but a majority of 4 is 3 — a split vote fails
CONSTRAINTS
  • 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 even n, 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.
SOLVE IT YOURSELF

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.

YOUR TASK

Implement election_result(n, grants): count 1 (self) plus the granted votes, and return whether that reaches the majority threshold ⌊n/2⌋ + 1.

HINTS — 4 IDEAS
  1. Total votes = 1 (the candidate’s own) + the number of True entries in grants.
  2. The threshold to win is n // 2 + 1 — a strict majority of the whole cluster, not of those who replied.
  3. Return total_votes >= threshold.
  4. 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.
CPython · WebAssembly

Explore the topic

See this challenge alongside everything else on the same subject — handbooks, system designs, algorithms and tools, in one place.