AlgoMaster Logo
AlgoMasterBuild a Saga Compensation Ordermedium

Build a Saga Compensation Order

medium

A saga implements a distributed business transaction as a sequence of local transactions. Because there is no global database rollback, a later failure must be handled by compensating the local steps that already completed.

Design a SagaCompensator class:

  • SagaCompensator() creates a stateless compensation planner.
  • String[] compensationOrder(String[] steps, int failAt) returns the completed steps whose compensations must run, in execution order.

steps lists the forward saga steps in order. failAt is the index of the first step that did not complete. Therefore, only steps[0] through steps[failAt - 1] committed work and need compensation. Return those names in reverse order.

failAt may equal steps.length. This means every listed step completed and the failure occurred immediately afterward, so every listed step must be compensated. When failAt is 0, nothing completed and the result is empty.

Example 1:

Input:

Output:

Explanation: reserve and charge completed before ship failed. Undo the most recent completed step first: compensate charge, then reserve.

Example 2:

Input:

Output:

Explanation: All listed steps completed before a later failure, so the saga unwinds the entire sequence from last to first.

Constraints

  • 1 <= steps.length <= 200
  • 1 <= steps[i].length <= 40
  • Step names contain printable ASCII characters.
  • 0 <= failAt <= steps.length
  • At most 100 calls are made to compensationOrder per object.
  • Calls are independent, and the input array must not be modified.
Hints

Loading...
CallReturns
new SagaCompensator()null
compensationOrder(["reserve","charge","ship","notify"], 2)["charge","reserve"]

Reserve and charge completed before ship failed at index 2, so their compensations run in reverse completion order.

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