AlgoMaster Logo
AlgoMasterPrint in Ordereasy

Print in Order

easy

Suppose we have a class Foo with three methods:

  • first() prints first.
  • second() prints second.
  • third() prints third.

The same Foo instance is passed to three threads. Thread A calls first(), thread B calls second(), and thread C calls third(). The threads may begin in any order.

Design the synchronization inside Foo so the callbacks always run in this order:

Each method receives a callback that produces its part of the output. Invoke each callback exactly once, and do not replace, change, or remove the callback call.

The judge creates and starts the threads. Your class should coordinate those threads rather than create additional threads itself. Waiting must not use busy-waiting or timing assumptions.

On Java and C#, preserve normal interruption behavior. If a waiting call is interrupted, it must exit without invoking its callback or advancing the sequence.

Standard concurrency APIs are preloaded, so you do not need import, include, package, or using statements.

Example 1:

Input:

Output:

Explanation: The threads already arrive in the required order.

Example 2:

Input:

Output:

Explanation: The thread calling third() waits. After first() completes, second() may run, and only then may third() run.

Constraints

  • arrivalOrder is a permutation of [1, 2, 3].
  • Exactly one thread calls each method on a Foo instance.
  • The three methods may be called concurrently in any order.
  • The callback must finish before the next callback begins.
  • Different Foo instances must be independent.
Loading...

Input

arrivalOrder = [1, 2, 3]

Output

firstsecondthird

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.