#1117

Building H2O

Medium
Concurrency
LeetCode ↗

Approaches

💡

Intuition

Time Space

In this approach, we simulate the process of forming water molecules by checking the current state of threads and waiting for the necessary number of each type to bond. This is a straightforward way to ensure that the conditions for forming water are met.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create counters for hydrogen and oxygen threads.
  2. 2Step 2: When a hydrogen thread arrives, check if there is an oxygen thread available. If not, wait.
  3. 3Step 3: When an oxygen thread arrives, check if there are two hydrogen threads available. If not, wait.
  4. 4Step 4: Once the required threads are available, bond them together and reset the counters.
solution.py27 lines
1from threading import Semaphore
2
3class H2O:
4    def __init__(self):
5        self.hydrogen_count = 0
6        self.oxygen_count = 0
7        self.h_lock = Semaphore(2)
8        self.o_lock = Semaphore(1)
9
10    def hydrogen(self, releaseHydrogen):
11        self.h_lock.acquire()
12        releaseHydrogen()  # release a hydrogen thread
13        self.hydrogen_count += 1
14        if self.hydrogen_count == 2 and self.oxygen_count > 0:
15            self.hydrogen_count = 0
16            self.oxygen_count = 0
17            self.o_lock.release()  # allow oxygen to bond
18
19    def oxygen(self, releaseOxygen):
20        self.o_lock.acquire()
21        releaseOxygen()  # release an oxygen thread
22        self.oxygen_count += 1
23        if self.oxygen_count == 1 and self.hydrogen_count == 2:
24            self.hydrogen_count = 0
25            self.oxygen_count = 0
26            self.h_lock.release()  # allow two hydrogens to bond
27

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.