Building H2O Problem
Description
LeetCode Problem 1117.
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. Hydrogen and oxygen threads will be given releaseHydrogen and releaseOxygen methods respectively, which will allow them to pass the barrier. These 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.
We do not have to worry about matching the threads up explicitly; the threads do not necessarily know which other threads they are paired up with. The key is that threads pass the barriers in complete sets; thus, if we examine the sequence of threads that bind and divide them into groups of three, each group should contain one oxygen and two hydrogen threads.
Write synchronization code for oxygen and hydrogen molecules that enforces these constraints.
Example 1:
Input: water = "HOH"
Output: "HHO"
Explanation: "HOH" and "OHH" are also valid answers.
Example 2:
Input: water = "OOHHHH"
Output: "HHOHHO"
Explanation: "HOHHHO", "OHHHHO", "HHOHOH", "HOHHOH", "OHHHOH", "HHOOHH", "HOHOHH" and "OHHOHH" are also valid answers.
Constraints:
3 * n == water.length1 <= n <= 20water[i]is either'H'or'O'.- There will be exactly
2 * n'H'inwater. - There will be exactly
n'O'inwater.
Solution
Approach: Hydrogen permits and an oxygen gate
A molecule is two hydrogens plus one oxygen, and the next molecule may not start before this one is complete. Model that with two semaphores:
hydrogenSlotsstarts at 2: at most two hydrogens may pass until an oxygen has completed the molecule.oxygenGatestarts at 0. Each hydrogen releases it once after printing, and the oxygen must acquire it twice, so it only proceeds after both hydrogens of its molecule have released theirs.- After printing, the oxygen gives back two hydrogen slots, which opens the next molecule.
- Several oxygen threads may be waiting at once. If two of them each grabbed one of the two permits, both would wait forever, so oxygens also take turns with a one-permit semaphore,
oxygenTurn, held from the start ofoxygenuntil the hydrogen slots are given back. (Java'sacquire(2)takes both permits atomically, so the Java version does not need it.)
A third hydrogen blocks on hydrogenSlots, and an early oxygen blocks on oxygenGate, so every group of three released characters has exactly two H and one O. Counting with semaphore permits (rather than testing a shared counter) avoids a race between the two hydrogen threads.
Complexity: O(1) work per call, O(1) extra space.
from threading import Semaphore
class H2O:
def __init__(self):
self.hydrogen_slots = Semaphore(2)
self.oxygen_gate = Semaphore(0)
self.oxygen_turn = Semaphore(1)
def hydrogen(self, releaseHydrogen: 'Callable[[], None]') -> None:
self.hydrogen_slots.acquire()
releaseHydrogen()
self.oxygen_gate.release()
def oxygen(self, releaseOxygen: 'Callable[[], None]') -> None:
self.oxygen_turn.acquire()
self.oxygen_gate.acquire()
self.oxygen_gate.acquire()
releaseOxygen()
self.hydrogen_slots.release()
self.hydrogen_slots.release()
self.oxygen_turn.release()