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.
Five silent philosophers sit at a round table with bowls of spaghetti. Forks are placed between each pair of adjacent philosophers.
Each philosopher must alternately think and eat. However, a philosopher can only eat spaghetti when they have both left and right forks. Each fork can be held by only one philosopher and so a philosopher can use the fork only if it is not being used by another philosopher. After an individual philosopher finishes eating, they need to put down both forks so that the forks become available to others. A philosopher can take the fork on their right or the one on their left as they become available, but cannot start eating before getting both forks.
Eating is not limited by the remaining amounts of spaghetti or stomach space; an infinite supply and an infinite demand are assumed.
Design a discipline of behaviour (a concurrent algorithm) such that no philosopher will starve; i.e., each can forever continue to alternate between eating and thinking, assuming that no philosopher can know when others may want to eat or think.
The problem statement and the image above are taken from wikipedia.org
The philosophers' ids are numbered from 0 to 4 in a clockwise order. Implement the function void wantsToEat(philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork) where:
philosopher is the id of the philosopher who wants to eat.pickLeftFork and pickRightFork are functions you can call to pick the corresponding forks of that philosopher.eat is a function you can call to let the philosopher eat once he has picked both forks.putLeftFork and putRightFork are functions you can call to put down the corresponding forks of that philosopher.Five threads, each representing a philosopher, will simultaneously use one object of your class to simulate the process. The function may be called for the same philosopher more than once, even before the last call ends.
Example 1:
Input: n = 1
Output: [[3,2,1],[3,1,1],[3,0,3],[3,1,2],[3,2,2],[4,2,1],[4,1,1],[2,2,1],[2,1,1],[1,2,1],[2,0,3],[2,1,2],[2,2,2],[4,0,3],[4,1,2],[4,2,2],[1,1,1],[1,0,3],[1,1,2],[1,2,2],[0,1,1],[0,2,1],[0,0,3],[0,1,2],[0,2,2]]
Explanation:
n is the number of times each philosopher will call the function.
The output array describes the calls you made to the functions controlling the forks and the eat function, its format is:
output[i] = [a, b, c] (three integers)
- a is the id of a philosopher.
- b specifies the fork: {1 : left, 2 : right}.
- c specifies the operation: {1 : pick, 2 : put, 3 : eat}.
Constraints:
1 <= n <= 60Problem summary: Five silent philosophers sit at a round table with bowls of spaghetti. Forks are placed between each pair of adjacent philosophers. Each philosopher must alternately think and eat. However, a philosopher can only eat spaghetti when they have both left and right forks. Each fork can be held by only one philosopher and so a philosopher can use the fork only if it is not being used by another philosopher. After an individual philosopher finishes eating, they need to put down both forks so that the forks become available to others. A philosopher can take the fork on their right or the one on their left as they become available, but cannot start eating before getting both forks. Eating is not limited by the remaining amounts of spaghetti or stomach space; an infinite supply and an infinite demand are assumed. Design a discipline of behaviour (a concurrent algorithm) such that no philosopher
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: General problem-solving
1
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1226: The Dining Philosophers
// Auto-generated Java example from py.
class Solution {
public void exampleSolution() {
}
}
// Reference (py):
// # Accepted solution for LeetCode #1226: The Dining Philosophers
// # Time: O(n)
// # Space: O(1)
//
// import threading
//
//
// class DiningPhilosophers(object):
// def __init__(self):
// self._l = [threading.Lock() for _ in xrange(5)]
//
// # call the functions directly to execute, for example, eat()
// def wantsToEat(self, philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork):
// """
// :type philosopher: int
// :type pickLeftFork: method
// :type pickRightFork: method
// :type eat: method
// :type putLeftFork: method
// :type putRightFork: method
// :rtype: void
// """
// left, right = philosopher, (philosopher+4)%5
// first, second = left, right
// if philosopher%2 == 0:
// first, second = left, right
// else:
// first, second = right, left
//
// with self._l[first]:
// with self._l[second]:
// pickLeftFork()
// pickRightFork()
// eat()
// putLeftFork()
// putRightFork()
// Accepted solution for LeetCode #1226: The Dining Philosophers
// Auto-generated Go example from py.
func exampleSolution() {
}
// Reference (py):
// # Accepted solution for LeetCode #1226: The Dining Philosophers
// # Time: O(n)
// # Space: O(1)
//
// import threading
//
//
// class DiningPhilosophers(object):
// def __init__(self):
// self._l = [threading.Lock() for _ in xrange(5)]
//
// # call the functions directly to execute, for example, eat()
// def wantsToEat(self, philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork):
// """
// :type philosopher: int
// :type pickLeftFork: method
// :type pickRightFork: method
// :type eat: method
// :type putLeftFork: method
// :type putRightFork: method
// :rtype: void
// """
// left, right = philosopher, (philosopher+4)%5
// first, second = left, right
// if philosopher%2 == 0:
// first, second = left, right
// else:
// first, second = right, left
//
// with self._l[first]:
// with self._l[second]:
// pickLeftFork()
// pickRightFork()
// eat()
// putLeftFork()
// putRightFork()
# Accepted solution for LeetCode #1226: The Dining Philosophers
# Time: O(n)
# Space: O(1)
import threading
class DiningPhilosophers(object):
def __init__(self):
self._l = [threading.Lock() for _ in xrange(5)]
# call the functions directly to execute, for example, eat()
def wantsToEat(self, philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork):
"""
:type philosopher: int
:type pickLeftFork: method
:type pickRightFork: method
:type eat: method
:type putLeftFork: method
:type putRightFork: method
:rtype: void
"""
left, right = philosopher, (philosopher+4)%5
first, second = left, right
if philosopher%2 == 0:
first, second = left, right
else:
first, second = right, left
with self._l[first]:
with self._l[second]:
pickLeftFork()
pickRightFork()
eat()
putLeftFork()
putRightFork()
// Accepted solution for LeetCode #1226: The Dining Philosophers
use std::sync::Condvar;
use std::sync::Mutex;
struct DiningPhilosophers {
eating: (Mutex<i32>, Condvar),
}
impl DiningPhilosophers {
fn new() -> Self {
let eating = (Mutex::new(-1), Condvar::new());
DiningPhilosophers { eating }
}
fn wants_to_eat(
&self,
philosopher: i32,
pick_left_fork: impl Fn(),
pick_right_fork: impl Fn(),
eat: impl Fn(),
put_left_fork: impl Fn(),
put_right_fork: impl Fn(),
) {
let (lock, cvar) = &self.eating;
let mut g = cvar
.wait_while(lock.lock().unwrap(), |eating| *eating != -1)
.unwrap();
*g = philosopher;
pick_left_fork();
pick_right_fork();
eat();
put_left_fork();
put_right_fork();
*g = -1;
cvar.notify_all();
}
}
#[test]
fn test() {
use std::sync::mpsc::channel;
use std::sync::Arc;
use threadpool::ThreadPool;
let pool = ThreadPool::new(5);
let dining_philosophers = Arc::new(DiningPhilosophers::new());
let n = 1;
let (tx, rx) = channel();
for _ in 0..n {
for i in 0..5 {
let dining_philosophers = dining_philosophers.clone();
let tx = tx.clone();
pool.execute(move || {
dining_philosophers.wants_to_eat(
i,
|| tx.send(vec![i, 1, 1]).unwrap(),
|| tx.send(vec![i, 2, 1]).unwrap(),
|| tx.send(vec![i, 0, 3]).unwrap(),
|| tx.send(vec![i, 1, 2]).unwrap(),
|| tx.send(vec![i, 2, 2]).unwrap(),
)
});
}
}
pool.join();
let res: Vec<Vec<i32>> = rx.try_iter().collect();
let ans = vec_vec_i32![
[4, 2, 1],
[4, 1, 1],
[0, 1, 1],
[2, 2, 1],
[2, 1, 1],
[2, 0, 3],
[2, 1, 2],
[2, 2, 2],
[4, 0, 3],
[4, 1, 2],
[0, 2, 1],
[4, 2, 2],
[3, 2, 1],
[3, 1, 1],
[0, 0, 3],
[0, 1, 2],
[0, 2, 2],
[1, 2, 1],
[1, 1, 1],
[3, 0, 3],
[3, 1, 2],
[3, 2, 2],
[1, 0, 3],
[1, 1, 2],
[1, 2, 2]
];
assert_eq!(res.len(), ans.len());
}
// Accepted solution for LeetCode #1226: The Dining Philosophers
// Auto-generated TypeScript example from py.
function exampleSolution(): void {
}
// Reference (py):
// # Accepted solution for LeetCode #1226: The Dining Philosophers
// # Time: O(n)
// # Space: O(1)
//
// import threading
//
//
// class DiningPhilosophers(object):
// def __init__(self):
// self._l = [threading.Lock() for _ in xrange(5)]
//
// # call the functions directly to execute, for example, eat()
// def wantsToEat(self, philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork):
// """
// :type philosopher: int
// :type pickLeftFork: method
// :type pickRightFork: method
// :type eat: method
// :type putLeftFork: method
// :type putRightFork: method
// :rtype: void
// """
// left, right = philosopher, (philosopher+4)%5
// first, second = left, right
// if philosopher%2 == 0:
// first, second = left, right
// else:
// first, second = right, left
//
// with self._l[first]:
// with self._l[second]:
// pickLeftFork()
// pickRightFork()
// eat()
// putLeftFork()
// putRightFork()
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.