AlgoMaster Logo
AlgoMasterDesign a Recursive Accumulatormedium

Design a Recursive Accumulator

medium

Design a thread-safe accumulator whose update operation is recursive.

Implement the RecursiveAccumulator class:

  • addRange(n, onAdd) adds n + (n - 1) + ... + 1 to the accumulated total. After each individual value is added, it invokes onAdd exactly once.
  • getTotal() returns the current total.

If n <= 0, addRange does nothing and must not invoke onAdd.

Each call to addRange must be one exclusive operation. Calls using the same accumulator cannot overlap each other, and getTotal cannot observe a partially completed range. The intended implementation recursively calls the locked operation, so languages with reentrant locks may let the same thread acquire the lock again at every recursive level.

Go's standard mutex is not reentrant. In Go, acquire the mutex once in AddRange, then perform the recursion in a private helper that assumes the mutex is already held.

If onAdd throws an unchecked exception or panics, the original failure must continue to the caller and the lock must still be released. Values added before the failure remain in the total.

Different RecursiveAccumulator instances must be independent.

The judge creates all caller threads and supplies the callbacks. Standard concurrency, callback, lock, and thread APIs are preloaded, so you do not need import, include, package, or using statements.

Example 1:

Input:

Output:

Explanation: The operation adds 3, 2, and 1, invoking onAdd after each addition.

Example 2:

Input:

Output:

Explanation: One complete recursive operation finishes before the other starts. The order between the two callers is unspecified.

Constraints

  • -10 <= n <= 500
  • At most 100 threads use one accumulator at a time.
  • At most 50000 total method calls are made per instance.
  • The final total fits in a signed 64-bit integer.
  • A callback may complete normally or fail with an unchecked exception or panic.
  • A callback does not call methods on the same accumulator.
  • Judge threads are not interrupted while waiting for the lock.
Loading...

Input

accumulator.addRange(3, onAdd)

Output

total = 6, onAdd calls = 3

Run is a quick check against the first couple of scenarios, which is roughly what these examples describe. Submit puts your class under the full set, which stays hidden.