Building H2O — LeetCode 1117 Python Solution
MediumConcurrency
- Problem
- #1117
- Reading time
- 3 min
- Source
- leetcode.com
The problem
There are two kinds of threads: oxygen and hydrogen. Your goal is to group these threads to form water molecules.
Example
- Input
- water = "HOH"
- Output
- "HHO"
- Explanation
- "HOH" and "OHH" are also valid answers.
Python solution
Python
from threading import Semaphore
class H2O:
def __init__(self):
self.h = Semaphore(2)
self.o = Semaphore(0)
def hydrogen(self, releaseHydrogen: "Callable[[], None]") -> None:
self.h.acquire()
# releaseHydrogen() outputs "H". Do not change or remove this line.
releaseHydrogen()
if self.h._value == 0:
self.o.release()
def oxygen(self, releaseOxygen: "Callable[[], None]") -> None:
self.o.acquire()
# releaseOxygen() outputs "O". Do not change or remove this line.
releaseOxygen()
self.h.release(2)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) to O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 1117. Building H2O?
- LeetCode 1117. Building H2O is rated Medium on LeetCode.
- What topics does LeetCode 1117. Building H2O cover?
- LeetCode 1117. Building H2O is tagged Concurrency on LeetCode.