Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using core interview patterns strategy.
There are two kinds of threads: oxygen and hydrogen. Your goal is to group these threads to form water molecules.
There is a barrier where each thread has to wait until a complete molecule can be formed. Hydrogen and oxygen threads will be given releaseHydrogen and releaseOxygen methods respectively, which will allow them to pass the barrier. These threads should pass the barrier in groups of three, and they must immediately bond with each other to form a water molecule. You must guarantee that all the threads from one molecule bond before any other threads from the next molecule do.
In other words:
We do not have to worry about matching the threads up explicitly; the threads do not necessarily know which other threads they are paired up with. The key is that threads pass the barriers in complete sets; thus, if we examine the sequence of threads that bind and divide them into groups of three, each group should contain one oxygen and two hydrogen threads.
Write synchronization code for oxygen and hydrogen molecules that enforces these constraints.
Example 1:
Input: water = "HOH" Output: "HHO" Explanation: "HOH" and "OHH" are also valid answers.
Example 2:
Input: water = "OOHHHH" Output: "HHOHHO" Explanation: "HOHHHO", "OHHHHO", "HHOHOH", "HOHHOH", "OHHHOH", "HHOOHH", "HOHOHH" and "OHHOHH" are also valid answers.
Constraints:
3 * n == water.length1 <= n <= 20water[i] is either 'H' or 'O'.2 * n 'H' in water.n 'O' in water.Problem summary: There are two kinds of threads: oxygen and hydrogen. Your goal is to group these threads to form water molecules. There is a barrier where each thread has to wait until a complete molecule can be formed. Hydrogen and oxygen threads will be given releaseHydrogen and releaseOxygen methods respectively, which will allow them to pass the barrier. These threads should pass the barrier in groups of three, and they must immediately bond with each other to form a water molecule. You must guarantee that all the threads from one molecule bond before any other threads from the next molecule do. In other words: If an oxygen thread arrives at the barrier when no hydrogen threads are present, it must wait for two hydrogen threads. If a hydrogen thread arrives at the barrier when no other threads are present, it must wait for an oxygen thread and another hydrogen thread. We do not have to worry about
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: General problem-solving
"HOH"
"OOHHHH"
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1117: Building H2O
class H2O {
private Semaphore h = new Semaphore(2);
private Semaphore o = new Semaphore(0);
public H2O() {
}
public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
h.acquire();
// releaseHydrogen.run() outputs "H". Do not change or remove this line.
releaseHydrogen.run();
o.release();
}
public void oxygen(Runnable releaseOxygen) throws InterruptedException {
o.acquire(2);
// releaseOxygen.run() outputs "O". Do not change or remove this line.
releaseOxygen.run();
h.release(2);
}
}
// Accepted solution for LeetCode #1117: Building H2O
// Auto-generated Go example from java.
func exampleSolution() {
}
// Reference (java):
// // Accepted solution for LeetCode #1117: Building H2O
// class H2O {
// private Semaphore h = new Semaphore(2);
// private Semaphore o = new Semaphore(0);
//
// public H2O() {
// }
//
// public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
// h.acquire();
// // releaseHydrogen.run() outputs "H". Do not change or remove this line.
// releaseHydrogen.run();
// o.release();
// }
//
// public void oxygen(Runnable releaseOxygen) throws InterruptedException {
// o.acquire(2);
// // releaseOxygen.run() outputs "O". Do not change or remove this line.
// releaseOxygen.run();
// h.release(2);
// }
// }
# Accepted solution for LeetCode #1117: Building H2O
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)
// Accepted solution for LeetCode #1117: Building H2O
use std::sync::Condvar;
use std::sync::Mutex;
struct H2O {
balance: (Mutex<(i32, i32)>, Condvar),
}
impl H2O {
fn new() -> Self {
let balance = (Mutex::new((0, 0)), Condvar::new());
H2O { balance }
}
fn hydrogen(&self, release_hydrogen: impl FnOnce()) {
let (lock, cvar) = &self.balance;
let mut g = cvar
.wait_while(lock.lock().unwrap(), |balance| balance.0 == 2)
.unwrap();
g.0 += 1;
if *g == (2, 1) {
*g = (0, 0);
}
release_hydrogen();
cvar.notify_all();
}
fn oxygen(&self, release_oxygen: impl FnOnce()) {
let (lock, cvar) = &self.balance;
let mut g = cvar
.wait_while(lock.lock().unwrap(), |balance| balance.1 == 1)
.unwrap();
g.1 += 1;
if *g == (2, 1) {
*g = (0, 0);
}
release_oxygen();
cvar.notify_all();
}
}
#[test]
fn test() {
use std::sync::mpsc::channel;
use std::sync::Arc;
use threadpool::ThreadPool;
let (tx, rx) = channel();
let water = "OOHHHH".to_string();
let h2o = Arc::new(H2O::new());
let pool = ThreadPool::new(2);
for m in water.chars() {
let h2o = h2o.clone();
let tx = tx.clone();
pool.execute(move || match m {
'H' => h2o.hydrogen(|| tx.send('H').unwrap()),
'O' => h2o.oxygen(|| tx.send('O').unwrap()),
_ => {}
});
}
pool.join();
let res: Vec<char> = rx.try_iter().collect();
assert_eq!(res.len(), 6);
let ohh = vec!['O', 'H', 'H'];
let hoh = vec!['H', 'O', 'H'];
let hho = vec!['H', 'H', 'O'];
let all = vec![ohh, hoh, hho];
for w in res.chunks(3) {
assert!(all.iter().any(|x| x == w));
}
}
// Accepted solution for LeetCode #1117: Building H2O
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1117: Building H2O
// class H2O {
// private Semaphore h = new Semaphore(2);
// private Semaphore o = new Semaphore(0);
//
// public H2O() {
// }
//
// public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
// h.acquire();
// // releaseHydrogen.run() outputs "H". Do not change or remove this line.
// releaseHydrogen.run();
// o.release();
// }
//
// public void oxygen(Runnable releaseOxygen) throws InterruptedException {
// o.acquire(2);
// // releaseOxygen.run() outputs "O". Do not change or remove this line.
// releaseOxygen.run();
// h.release(2);
// }
// }
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.