Building H2O - Problem
Imagine a molecular assembly line where oxygen and hydrogen threads arrive randomly, but they must form water molecules (HโO) in perfect groups of three: exactly 2 hydrogen + 1 oxygen.
Your challenge is to implement a synchronization barrier that ensures threads pass through in complete molecular sets. No thread can proceed alone - they must wait for their molecular partners!
The Rules:
- ๐งช Perfect Molecules: Every group of 3 threads must contain exactly 2 hydrogen and 1 oxygen
- โณ Patient Waiting: If an oxygen thread arrives but there aren't 2 hydrogen threads ready, it must wait
- ๐ Complete Bonding: All 3 threads from one molecule must bond completely before any threads from the next molecule start
- ๐ฏ Atomic Groups: Threads pass the barrier in indivisible groups of three
You'll implement two methods: hydrogen() and oxygen() that handle the synchronization logic. Each method calls releaseHydrogen() or releaseOxygen() respectively when it's safe to proceed.
Input & Output
example_1.py โ Basic Molecule Formation
$
Input:
Thread sequence: "OOHHHH"
โบ
Output:
Possible output: "HHOHHO" or "HOHHOH"
๐ก Note:
6 threads arrive (2 oxygen, 4 hydrogen). They form 2 complete HโO molecules. The exact order within each molecule group may vary, but we get exactly 2 complete molecules.
example_2.py โ Perfect Balance
$
Input:
Thread sequence: "HHOHHO"
โบ
Output:
Possible output: "HHOHHO" or "HOHHOH"
๐ก Note:
Perfect input with exactly 2 molecules worth of threads. All threads can proceed immediately once their molecular partners arrive.
example_3.py โ Excess Hydrogen
$
Input:
Thread sequence: "HHHHHHO"
โบ
Output:
Output: "HHO" (3 threads released, 4 threads wait)
๐ก Note:
Only 1 complete molecule can be formed. 2 hydrogen threads and 1 oxygen thread are released, while 4 hydrogen threads remain waiting for more oxygen threads.
Constraints
- 1 โค total threads โค 1000
- Each thread is either hydrogen ('H') or oxygen ('O')
- Threads may arrive in any order
- Must guarantee atomic molecule formation
- Solution must be thread-safe and deadlock-free
Visualization
Tap to expand
Understanding the Visualization
1
Atoms Arrive
Hydrogen and oxygen atoms arrive randomly at the assembly line
2
Waiting Areas
Atoms wait in designated areas - hydrogen area (max 2), oxygen area (max 1)
3
Molecule Formation
When 2H + 1O are ready, they form a complete HโO molecule
4
Synchronized Release
All 3 atoms in the molecule are released together atomically
Key Takeaway
๐ฏ Key Insight: Semaphores act as intelligent waiting rooms that automatically coordinate the perfect 2:1 hydrogen-to-oxygen ratio, while barriers ensure atomic molecule release - no busy waiting, no waste!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code