![]() |
VOOZH | about |
Fizz Buzz problem states that given an integer n, for every integer i <= n, the task is to write a C++ program to print,
Example:
Input: n = 3
Output: [1 2 Fizz]Input: n = 10
Output: [1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz]Input: n = 20
Output: [1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz]
Table of Content
A very simple approach to solve this problem is that we can start checking each number from 1 to n to see if it's divisible by 3, 5, or both. Depending on the divisibility:
Below is the implementation of the above approach:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz
Time Complexity: O(n), since we need to traverse the numbers from 1 to n in any condition.
Auxiliary Space: O(n), for storing the result
While the naive approach works well for the basic FizzBuzz problem, it becomes very complicated if additional mappings comes under picture, such as "Jazz" for multiples of 7. The number of conditions for checking would increases.
Instead of checking every possible combination of divisors, we check each divisor separately and concatenate the corresponding strings if the number is divisible by them.
Let's see the step-by-step approach:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz
Time Complexity: O(n), since we need to traverse the numbers from 1 to n in any condition.
Auxiliary Space: O(n), for storing the result
When we have many words to add like "Fizz", "Buzz", "Jazz" and more, the second method can still get complicated. To make things cleaner, we can use something called a hash table (in C++, it's called unordered_map). Initially, we can store the divisors and their corresponding words into hash table.
For this problem, first we'll map 3 to "Fizz" and 5 to "Buzz" into unordered_map and for each number i <= n, do the following:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz
Time Complexity: O(n), since we need to traverse the numbers from 1 to n in any condition.
Auxiliary Space: O(n), for storing the result and for hash table