Building H2O — LeetCode 1117 Python Solution

MediumConcurrency
Problem
#1117
Reading time
3 min

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

MeasureComplexity
TimeO(n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview