Python 1195.py
from threading import Condition
class FizzBuzz:
def __init__(self, n: int):
self.step = 1
self.last = n
self.cv = Condition()
# all four functions are extremely similar
# printFizz() outputs "fizz"
def fizz(self, printFizz: 'Callable[[], None]') -> None:
with self.cv:
while self.step <= self.last:
if self.step % 3 == 0 and self.step % 5 != 0:
printFizz()
self.step += 1
self.cv.notifyAll()
else:
self.cv.wait()
# printBuzz() outputs "buzz"
def buzz(self, printBuzz: 'Callable[[], None]') -> None:
with self.cv:
while self.step <= self.last:
if self.step % 5 == 0 and self.step % 3 != 0:
printBuzz()
self.step += 1
self.cv.notifyAll()
else:
self.cv.wait()
# printFizzBuzz() outputs "fizzbuzz"
def fizzbuzz(self, printFizzBuzz: 'Callable[[], None]') -> None:
with self.cv:
while self.step <= self.last:
if self.step % 15 == 0:
printFizzBuzz()
self.step += 1
self.cv.notifyAll()
else:
self.cv.wait()
# printNumber(x) outputs "x", where x is an integer.
def number(self, printNumber: 'Callable[[int], None]') -> None:
with self.cv:
while self.step <= self.last:
if self.step % 3 != 0 and self.step % 5 != 0:
printNumber(self.step)
self.step += 1
self.cv.notifyAll()
else:
self.cv.wait()
Difficulty
and has an acceptance rate of about 75% (100k+ submissions).
Typical patterns to solve this problem:
- Concurrency
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a FizzBuzz class that coordinates four worker threads to emit the classic FizzBuzz sequence up to a given limit n. The class maintains a shared counter step and a Condition variable cv that synchronizes access among the threads. Each thread repeatedly checks whether the current value of step satisfies its own printing rule; if so, it performs the output, advances the counter, and notifies the other threads. Otherwise, it waits on the condition variable until another thread signals a state change.
Key Steps
Initialization
The constructor stores the target limit, initializes the counter at 1, and creates a Condition object that will be used for mutual exclusion and thread coordination.
def __init__(self, n: int):
self.step = 1
self.last = n
self.cv = Condition()
fizz method
The fizz method is responsible for printing the word “fizz” when the current number is divisible by 3 but not by 5. It acquires the condition lock, then loops while the counter has not exceeded the limit. Inside the loop, a modulo test determines eligibility. When the test succeeds, the supplied printFizz callable is invoked, the counter is incremented, and all waiting threads are awakened. If the test fails, the thread releases the lock and waits for a notification.
def fizz(self, printFizz: 'Callable[[], None]') -> None:
with self.cv:
while self.step <= self.last:
if self.step % 3 == 0 and self.step % 5 != 0:
printFizz()
self.step += 1
self.cv.notifyAll()
else:
self.cv.wait()
buzz method
The buzz method mirrors the structure of fizz but targets numbers divisible by 5 and not by 3. The same pattern of condition acquisition, modulo check, printing, counter increment, and notification is followed.
def buzz(self, printBuzz: 'Callable[[], None]') -> None:
with self.cv:
while self.step <= self.last:
if self.step % 5 == 0 and self.step % 3 != 0:
printBuzz()
self.step += 1
self.cv.notifyAll()
else:
self.cv.wait()
fizzbuzz method
The fizzbuzz method handles the case where a number is a multiple of both 3 and 5 (i.e., 15). Its condition check is a single modulo operation against 15, simplifying the logic for this combined case.
def fizzbuzz(self, printFizzBuzz: 'Callable[[], None]') -> None:
with self.cv:
while self.step <= self.last:
if self.step % 15 == 0:
printFizzBuzz()
self.step += 1
self.cv.notifyAll()
else:
self.cv.wait()
number method
The number method prints the numeric value when the current counter is not divisible by either 3 or 5. It passes the current step value to the supplied printNumber callable.
def number(self, printNumber: 'Callable[[int], None]') -> None:
with self.cv:
while self.step <= self.last:
if self.step % 3 != 0 and self.step % 5 != 0:
printNumber(self.step)
self.step += 1
self.cv.notifyAll()
else:
self.cv.wait()
Edge Cases Handled
The implementation explicitly distinguishes numbers that belong to overlapping categories. For instance, a value divisible by both 3 and 5 satisfies the fizzbuzz condition (step % 15 == 0) and is therefore excluded from the fizz and buzz branches, which each require the opposite divisor to be false. This ensures that “fizzbuzz” is printed exactly once for such numbers.
When the counter reaches the limit (self.step > self.last), each loop terminates, allowing the thread to exit cleanly. The condition variable guarantees that a thread waiting on a state that will never become true (e.g., after the limit is passed) will be released by the final notifyAll issued by the thread that performed the last increment.
The code also tolerates the situation where multiple threads are awakened simultaneously. Because each thread re-evaluates the condition after acquiring the lock, only the thread whose rule matches the current step proceeds, while the others immediately go back to waiting. This prevents duplicate outputs for the same number.
Performance Optimizations
The design avoids busy-waiting by using a Condition object. Threads block on cv.wait() when their specific rule does not apply, releasing the lock and allowing other threads to run. This reduces CPU consumption compared with a spin-loop approach.
All four worker methods share a single lock (self.cv). By holding the lock only for the brief critical section that checks the condition, prints, increments the counter, and notifies, the implementation minimizes contention. The increment operation is performed atomically within the locked region, guaranteeing that each number is processed exactly once.
The use of cv.notifyAll() rather than notify() ensures that any thread whose rule may now be satisfied receives a wake-up signal. Although this may awaken more threads than strictly necessary, it simplifies coordination and prevents missed notifications that could otherwise cause a thread to remain blocked indefinitely.
Modulo operations are inexpensive for small integers, and the code performs at most two modulo checks per iteration (three in the number method). This keeps the per-step overhead low while preserving clear logical separation of the four cases.
ELI5 - Simplified Explanation
Imagine there are four friends working together to count up to a big number, like a game of tag. They have a special referee who makes sure everyone takes the right turn. Each friend has a specific job to do based on the current number. One friend shouts fizz when the number can be divided by three, another shouts buzz when it can be divided by five, a third friend shouts fizzbuzz when it can be divided by both, and the last friend just says the number itself if none of the other rules apply.
They all stand in a circle and use a wait and signal tool controlled by the referee. When it is not a friend's turn to speak, that friend calmly waits for the signal from the others. Once someone finishes their job, they change the number to the next one and tell everyone else that it is time to check whose turn it is next. This keeps them moving in order, making sure the game flows smoothly without anyone talking over each other until they reach the final goal.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||
|---|---|---|---|---|---|---|
| author | solutions | |||||
| www | AlgoMonster | C++ | Python | Java | TS | |
| WalkCCC | C++ | Python | Java | |||
| leetcode.ca | C++ | Python | Java | |||
| Progiez | C++ | Python | Java | |||
| github | black-shadows | C++ | ||||
| DimitrisJim | Python | |||||
| fsq | C++ | |||||
| keineahnung2345 | C++ | |||||
| Krazune | Java | |||||
| lkwq007 | Python | |||||
| suxrobGM | C# | |||||
| varunu28 | Java | |||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||
| WalkCCC | C++, Python, Java | |||||
| leetcode.ca | C++, Java, Python | |||||
| Progiez | C++, Java, Python | |||||
| black-shadows | C++, C++ | |||||
| DimitrisJim | Python | |||||
| fsq | C++ | |||||
| keineahnung2345 | C++ | |||||
| Krazune | Java | |||||
| lkwq007 | Python | |||||
| suxrobGM | C# | |||||
| varunu28 | Java |
Videos
Similar Problems
- problem 1116: Print Zero Even Odd
Solved On The Same Day
- problem 2280: Minimum Lines to Represent a Line Chart
- problem 3163: String Compression III
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality