#1195
Fizz Buzz Multithreaded
MediumConcurrencyConcurrencyThread Synchronization
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a single shared counter and manages the printing of 'fizz', 'buzz', 'fizzbuzz', and numbers in a synchronized manner. This reduces the overhead of multiple threads and ensures that the output is in the correct order.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a shared counter to 1.
- 2Step 2: Create four threads for fizz, buzz, fizzbuzz, and number.
- 3Step 3: Each thread checks the counter and prints the appropriate output while incrementing the counter in a synchronized manner.
solution.py43 lines
1import threading
2
3class FizzBuzz:
4 def __init__(self, n):
5 self.n = n
6 self.current = 1
7 self.lock = threading.Lock()
8
9 def fizz(self, printFizz):
10 while True:
11 with self.lock:
12 if self.current > self.n:
13 return
14 if self.current % 3 == 0 and self.current % 5 != 0:
15 printFizz()
16 self.current += 1
17
18 def buzz(self, printBuzz):
19 while True:
20 with self.lock:
21 if self.current > self.n:
22 return
23 if self.current % 5 == 0 and self.current % 3 != 0:
24 printBuzz()
25 self.current += 1
26
27 def fizzbuzz(self, printFizzBuzz):
28 while True:
29 with self.lock:
30 if self.current > self.n:
31 return
32 if self.current % 3 == 0 and self.current % 5 == 0:
33 printFizzBuzz()
34 self.current += 1
35
36 def number(self, printNumber):
37 while True:
38 with self.lock:
39 if self.current > self.n:
40 return
41 if self.current % 3 != 0 and self.current % 5 != 0:
42 printNumber(self.current)
43 self.current += 1ℹ
Complexity note: The time complexity is O(n) because we only iterate through the numbers once, and each thread checks the condition in constant time.
- 1Understanding thread synchronization is crucial for multithreaded problems.
- 2Managing shared state between threads effectively avoids race conditions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.