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.
Build confidence with an intuition-first walkthrough focused on core interview patterns fundamentals.
Suppose we have a class:
public class Foo {
public void first() { print("first"); }
public void second() { print("second"); }
public void third() { print("third"); }
}
The same instance of Foo will be passed to three different threads. Thread A will call first(), thread B will call second(), and thread C will call third(). Design a mechanism and modify the program to ensure that second() is executed after first(), and third() is executed after second().
Note:
We do not know how the threads will be scheduled in the operating system, even though the numbers in the input seem to imply the ordering. The input format you see is mainly to ensure our tests' comprehensiveness.
Example 1:
Input: nums = [1,2,3] Output: "firstsecondthird" Explanation: There are three threads being fired asynchronously. The input [1,2,3] means thread A calls first(), thread B calls second(), and thread C calls third(). "firstsecondthird" is the correct output.
Example 2:
Input: nums = [1,3,2] Output: "firstsecondthird" Explanation: The input [1,3,2] means thread A calls first(), thread B calls third(), and thread C calls second(). "firstsecondthird" is the correct output.
Constraints:
nums is a permutation of [1, 2, 3].Problem summary: Suppose we have a class: public class Foo { public void first() { print("first"); } public void second() { print("second"); } public void third() { print("third"); } } The same instance of Foo will be passed to three different threads. Thread A will call first(), thread B will call second(), and thread C will call third(). Design a mechanism and modify the program to ensure that second() is executed after first(), and third() is executed after second(). Note: We do not know how the threads will be scheduled in the operating system, even though the numbers in the input seem to imply the ordering. The input format you see is mainly to ensure our tests' comprehensiveness.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: General problem-solving
[1,2,3]
[1,3,2]
print-foobar-alternately)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1114: Print in Order
class Foo {
private Semaphore a = new Semaphore(1);
private Semaphore b = new Semaphore(0);
private Semaphore c = new Semaphore(0);
public Foo() {
}
public void first(Runnable printFirst) throws InterruptedException {
a.acquire(1);
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
b.release(1);
}
public void second(Runnable printSecond) throws InterruptedException {
b.acquire(1);
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
c.release(1);
}
public void third(Runnable printThird) throws InterruptedException {
c.acquire(1);
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
a.release(1);
}
}
// Accepted solution for LeetCode #1114: Print in Order
// Auto-generated Go example from java.
func exampleSolution() {
}
// Reference (java):
// // Accepted solution for LeetCode #1114: Print in Order
// class Foo {
// private Semaphore a = new Semaphore(1);
// private Semaphore b = new Semaphore(0);
// private Semaphore c = new Semaphore(0);
//
// public Foo() {
// }
//
// public void first(Runnable printFirst) throws InterruptedException {
// a.acquire(1);
// // printFirst.run() outputs "first". Do not change or remove this line.
// printFirst.run();
// b.release(1);
// }
//
// public void second(Runnable printSecond) throws InterruptedException {
// b.acquire(1);
// // printSecond.run() outputs "second". Do not change or remove this line.
// printSecond.run();
// c.release(1);
// }
//
// public void third(Runnable printThird) throws InterruptedException {
// c.acquire(1);
// // printThird.run() outputs "third". Do not change or remove this line.
// printThird.run();
// a.release(1);
// }
// }
# Accepted solution for LeetCode #1114: Print in Order
class Foo:
def __init__(self):
self.l2 = threading.Lock()
self.l3 = threading.Lock()
self.l2.acquire()
self.l3.acquire()
def first(self, printFirst: 'Callable[[], None]') -> None:
printFirst()
self.l2.release()
def second(self, printSecond: 'Callable[[], None]') -> None:
self.l2.acquire()
printSecond()
self.l3.release()
def third(self, printThird: 'Callable[[], None]') -> None:
self.l3.acquire()
printThird()
// Accepted solution for LeetCode #1114: Print in Order
use std::sync::Condvar;
use std::sync::Mutex;
struct Foo {
seq: (Mutex<i32>, Condvar),
}
impl Foo {
fn new() -> Self {
let seq = (Mutex::new(1), Condvar::new());
Foo { seq }
}
fn first(&self, print_first: impl FnOnce()) {
let (lock, cvar) = &self.seq;
let mut g = cvar
.wait_while(lock.lock().unwrap(), |seq| *seq != 1)
.unwrap();
*g = 2;
print_first();
cvar.notify_all();
}
fn second(&self, print_second: impl FnOnce()) {
let (lock, cvar) = &self.seq;
let mut g = cvar
.wait_while(lock.lock().unwrap(), |seq| *seq != 2)
.unwrap();
*g = 3;
print_second();
cvar.notify_all();
}
fn third(&self, print_third: impl FnOnce()) {
let (lock, cvar) = &self.seq;
let mut g = cvar
.wait_while(lock.lock().unwrap(), |seq| *seq != 3)
.unwrap();
*g = 4;
print_third();
cvar.notify_all();
}
}
#[test]
fn test() {
use std::sync::mpsc::channel;
use std::sync::Arc;
use threadpool::ThreadPool;
let nums = vec![1, 2, 3];
let fooo = Arc::new(Foo::new());
let (tx, rx) = channel();
let pool = ThreadPool::new(4);
for x in nums {
let tx = tx.clone();
let fooo = fooo.clone();
pool.execute(move || match x {
1 => fooo.first(|| tx.send("first".to_string()).unwrap()),
2 => fooo.second(|| tx.send("second".to_string()).unwrap()),
3 => fooo.third(|| tx.send("third".to_string()).unwrap()),
_ => {}
})
}
pool.join();
let ss: Vec<String> = rx.try_iter().collect();
let res = ss.join("");
let ans = "firstsecondthird".to_string();
assert_eq!(ans, res);
let nums = vec![1, 3, 2];
let fooo = Arc::new(Foo::new());
let (tx, rx) = channel();
let pool = ThreadPool::new(4);
for x in nums {
let tx = tx.clone();
let fooo = fooo.clone();
pool.execute(move || match x {
1 => fooo.first(|| tx.send("first".to_string()).unwrap()),
2 => fooo.second(|| tx.send("second".to_string()).unwrap()),
3 => fooo.third(|| tx.send("third".to_string()).unwrap()),
_ => {}
})
}
pool.join();
let ss: Vec<String> = rx.try_iter().collect();
let res = ss.join("");
let ans = "firstsecondthird".to_string();
assert_eq!(ans, res);
}
// Accepted solution for LeetCode #1114: Print in Order
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1114: Print in Order
// class Foo {
// private Semaphore a = new Semaphore(1);
// private Semaphore b = new Semaphore(0);
// private Semaphore c = new Semaphore(0);
//
// public Foo() {
// }
//
// public void first(Runnable printFirst) throws InterruptedException {
// a.acquire(1);
// // printFirst.run() outputs "first". Do not change or remove this line.
// printFirst.run();
// b.release(1);
// }
//
// public void second(Runnable printSecond) throws InterruptedException {
// b.acquire(1);
// // printSecond.run() outputs "second". Do not change or remove this line.
// printSecond.run();
// c.release(1);
// }
//
// public void third(Runnable printThird) throws InterruptedException {
// c.acquire(1);
// // printThird.run() outputs "third". Do not change or remove this line.
// printThird.run();
// a.release(1);
// }
// }
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.