AlgoMaster Logo
AlgoMasterCalculate the Raft Commit Indexmedium

Calculate the Raft Commit Index

medium

A Raft leader tracks the greatest replicated log index for every server in matchIndex. An entry can advance the commit index when it is stored on a majority of servers. Raft also restricts this calculation to entries from the leader's current term.

Design a RaftCommitCalculator class:

  • RaftCommitCalculator() creates a stateless calculator.
  • int commitIndex(int[] matchIndex, int[] logTerms, int currentTerm) returns the greatest committable log index, or 0 if none qualifies.

Indices in matchIndex are one-based log positions. logTerms[i] is the term of log entry i + 1. A candidate N qualifies when:

Do not modify either input array.

Example 1:

Input:

Output:

Explanation: Three of five servers have index 3, which is a majority. Entry 3 belongs to term 2.

Example 2:

Input:

Output:

Explanation: A majority has replicated through index 2, but both entries through that frontier have older terms. Entry 3 is current-term but appears on only two servers.

Constraints

  • 1 <= matchIndex.length <= 10^5
  • 1 <= logTerms.length <= 10^5
  • 0 <= matchIndex[i] <= logTerms.length
  • 1 <= logTerms[i] <= currentTerm <= 10^9
  • logTerms is nondecreasing, as in a valid Raft log.
  • At most 100 calls are made to commitIndex.
Hints

Loading...
CallReturns
new RaftCommitCalculator()null
commitIndex([3,3,3,1,1], [1,2,2], 2)3

Three of five servers have replicated index 3, and log entry 3 belongs to current term 2.

Run checks these cases. Submit also runs a larger hidden set.