Leetcode 1195: Fizz Buzz Multithreaded

grid47
grid47
Exploring patterns and algorithms
Jul 10, 2024 6 min read

You are given a class FizzBuzz that has four methods: fizz(), buzz(), fizzbuzz(), and number(). These methods are executed by four different threads. The goal is to output a sequence of numbers from 1 to n with special rules: if the number is divisible by 3 and 5, print ‘fizzbuzz’; if divisible by 3 but not 5, print ‘fizz’; if divisible by 5 but not 3, print ‘buzz’; otherwise, print the number.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer `n`, representing the length of the sequence.
Example: Input: n = 10
Constraints:
• 1 <= n <= 50
Output: The output should be a list of values where each value corresponds to the number or one of the words 'fizz', 'buzz', or 'fizzbuzz'.
Example: Output: [1, 2, 'fizz', 4, 'buzz', 'fizz', 7, 8, 'fizz', 'buzz']
Constraints:
• The sequence should follow the correct order and the rules for 'fizz', 'buzz', and 'fizzbuzz'.
Goal: The goal is to implement the `FizzBuzz` class such that each method is responsible for printing the appropriate output based on the current number.
Steps:
• Create the `FizzBuzz` class with an initializer for the number `n`.
• Use synchronization (mutexes) to coordinate the threads for each method.
• Ensure the correct method is called based on whether the number is divisible by 3, 5, or both.
Goal: The solution should correctly handle small to moderate values of `n`, and ensure thread synchronization.
Steps:
• 1 <= n <= 50
• Handle synchronization correctly between the threads.
Assumptions:
• Each method (`fizz`, `buzz`, `fizzbuzz`, `number`) will be executed by a separate thread.
• The order of printing is important and must follow the rules for 'fizz', 'buzz', and 'fizzbuzz'.
Input: Input: n = 7
Explanation: The sequence from 1 to 7 will output: [1, 2, 'fizz', 4, 'buzz', 'fizz', 7]. 'fizz' is printed for multiples of 3, 'buzz' for multiples of 5, and the rest are the numbers themselves.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus