#1226

The Dining Philosophers

Medium
ConcurrencyMutexLocking mechanisms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

To avoid deadlock, we can enforce a rule where philosophers pick up the forks in a specific order. For example, if all philosophers pick up the right fork first, it ensures that at least one philosopher can always eat, preventing starvation.

⚙️

Algorithm

5 steps
  1. 1Step 1: Each philosopher will always pick up the right fork first.
  2. 2Step 2: If they can pick up the right fork, they then try to pick up the left fork.
  3. 3Step 3: If both forks are acquired, they eat.
  4. 4Step 4: After eating, they put down both forks.
  5. 5Step 5: Repeat the process.
solution.py20 lines
1import threading
2
3class DiningPhilosophers:
4    def __init__(self):
5        self.forks = [threading.Lock() for _ in range(5)]
6
7    def wantsToEat(self, philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork):
8        left = philosopher
9        right = (philosopher + 1) % 5
10        while True:
11            self.forks[right].acquire()
12            self.forks[left].acquire()
13            pickRightFork()
14            pickLeftFork()
15            eat()
16            putRightFork()
17            putLeftFork()
18            self.forks[left].release()
19            self.forks[right].release()
20            break

Complexity note: The time complexity is O(n) because each philosopher can potentially eat without waiting indefinitely, ensuring that they can continue their cycle of thinking and eating without deadlock.

  • 1Using a specific order for picking forks can prevent deadlock.
  • 2Concurrency problems often require careful resource management.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.