Leetcode problem on H2O

Link - https://leetcode.com/problems/building-h2o/
mail@pastecode.io avatar
unknown
java
7 months ago
901 B
37
Indexable
Never
class H2O {

    Semaphore HSema = new Semaphore(2);
    Semaphore OSema = new Semaphore(0);

    public H2O() {
        
    }

    public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
		HSema.acquire();
        // releaseHydrogen.run() outputs "H". Do not change or remove this line.
        releaseHydrogen.run();
        OSema.release();
    }

    public void oxygen(Runnable releaseOxygen) throws InterruptedException {
        OSema.acquire(2);
        // releaseOxygen.run() outputs "O". Do not change or remove this line.
		releaseOxygen.run();
        HSema.release(2);
    }
}

//In the above solution, in line no-18, why are we needing to acquire 2 oxygen semaphores? The question said to only print 1 oxygen atom for every 2 hydrogen atoms. 
// So this was not passing the test cases when letting oxygen sema to acquire only 1.