**Concurrency design problem (paper-only).** Threading primitives are not available in the gitGood sandbox; the auto-grader validates a *simulation* of the barrier protocol. The interview-grade answer uses two semaphores plus a barrier or a monitor.
There are two kinds of threads: `oxygen` and `hydrogen`. Your goal is to group these threads to form water molecules. There is a barrier where each thread has to wait until a complete molecule can be formed (one oxygen + two hydrogens). Threads should pass the barrier in groups of three, and they must immediately bond with each other to form a water molecule. You must guarantee that all the threads from one molecule bond before any other threads from the next molecule do.
In other words:
- If an oxygen thread arrives at the barrier when no hydrogen threads are present, it must wait for two hydrogen threads.
- If a hydrogen thread arrives at the barrier when no other threads are present, it must wait for an oxygen thread and another hydrogen thread.
**For the auto-grader:** given a string `arrivals` of `'H'` and `'O'` characters representing arrival order at the barrier, return the molecule release order as a string. Each molecule is encoded as the three letters that crossed the barrier together, in their barrier-release order (always two H followed by one O - "HHO"). If the input doesn't form complete molecules, only return completed ones.
Example 1
Input:arrivals = "HOH"
Output:"HHO"
Explanation:Two H's and one O combine. Release order is the two H's then the O.
Example 2
Input:arrivals = "OOHHHH"
Output:"HHOHHO"
Explanation:Two molecules form: the first O pairs with the first two H's; the second O pairs with the next two H's.
Constraints
- 0 <= arrivals.length <= 3000
- arrivals consists only of 'H' and 'O'
- Total H's and O's may not pair up perfectly; ignore the leftover.