AlgoMaster Logo
AlgoMasterSimulate a Three-Phase Commit Participantmedium

Simulate a Three-Phase Commit Participant

medium

Three-phase commit adds a precommit phase between voting and the final commit decision. In the simplified timing model used by this exercise, that extra phase lets a participant decide after losing contact with the coordinator.

Design a ThreePhaseCommitParticipant class:

  • ThreePhaseCommitParticipant() creates a stateless simulator.
  • String finalState(String[] messages) processes one participant's messages in order and returns its final state.

The participant starts in "initial". Apply these rules:

  • "prepare" changes "initial" to "ready".
  • "precommit" changes "ready" to "precommit".
  • "commit" changes "precommit" to "committed".
  • "abort" changes any active state to "aborted".
  • "timeout" changes "precommit" to "committed", but changes "initial" or "ready" to "aborted".

The states "committed" and "aborted" are terminal. Each input is a valid protocol trace: normal phase messages appear only in the state where they apply, and an "abort" or "timeout", when present, is the final message.

Example 1:

Input:

Output:

Explanation: The participant moves from initial to ready, then precommit, and finally committed.

Example 2:

Input:

Output:

Explanation: Reaching precommit means the unanimous prepare result was announced. Under the exercise's assumptions, the participant can commit when the coordinator times out.

Constraints

  • 1 <= messages.length <= 4
  • messages[i] is "prepare", "precommit", "commit", "abort", or "timeout".
  • Normal phase messages form a valid prefix of prepare, precommit, commit.
  • abort or timeout, when present, is the final message.
  • Return exactly one of "initial", "ready", "precommit", "committed", or "aborted".
  • At most 100 calls are made to finalState per object, and calls are independent.
Hints

Loading...
CallReturns
new ThreePhaseCommitParticipant()null
finalState(["prepare","precommit","commit"])"committed"

The participant follows all three normal phases: initial to ready to precommit to committed.

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