LeetCode 1117: Building H2O Solution
Master LeetCode problem 1117 (Building H2O), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1117. Building H2O
Problem Explanation
Explanation
To solve this problem, we can use two semaphores - one for hydrogen and one for oxygen. We also need a counter to keep track of the number of hydrogen molecules formed so far. Each hydrogen thread will first acquire the semaphore for hydrogen. If the required number of hydrogen molecules are already formed, it will release the semaphore for oxygen to allow an oxygen thread to pass. If not, it will wait. Similarly, an oxygen thread will acquire the semaphore for oxygen and wait until the required number of hydrogen molecules are formed. Once the required number of hydrogen molecules are formed, the oxygen thread will release the semaphore for hydrogen to allow two hydrogen threads to pass. This way, we ensure that the threads pass the barrier in groups of three to form water molecules.
Time Complexity: O(n), where n is the number of water molecules. Space Complexity: O(1)
Solution Code
import java.util.concurrent.Semaphore;
class H2O {
Semaphore hSemaphore, oSemaphore;
int hCount;
public H2O() {
hSemaphore = new Semaphore(2);
oSemaphore = new Semaphore(1);
hCount = 0;
}
public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
hSemaphore.acquire();
releaseHydrogen.run();
synchronized(this) {
hCount++;
if(hCount == 2) {
hCount = 0;
oSemaphore.release();
}
}
}
public void oxygen(Runnable releaseOxygen) throws InterruptedException {
oSemaphore.acquire();
releaseOxygen.run();
hSemaphore.release(2);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1117 (Building H2O)?
This page provides optimized solutions for LeetCode problem 1117 (Building H2O) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1117 (Building H2O)?
The time complexity for LeetCode 1117 (Building H2O) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1117 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1117 in Java, C++, or Python.