Difficulty: Easy, Asked-In: Google, Microsoft, Amazon.
Key takeaway: The FizzBuzz game is a popular problem that is more about learning basic programming concepts like if-else, loops, string operations, mathematical operations, etc.
This game is played in a group, where players take turns to say the next number in a sequence, counting one at a time.
Given a number n, write a program that outputs the string representation of numbers from 1 to n. We need to return a string array as an output (1-indexed) where:
Input: n = 15
Output: ["1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz"]
The most basic solution is to run a loop from 1 to n and use the modulus operation. In this loop, we use a sequence of conditional statements to check whether each integer is divisible by 3, 5, or both. When one of the conditional statements returns true, we store the appropriate string value at the ith index in the output[] string. After the loop, we return the output[] string.
fizzBuzzGame(n)
output = array of n strings
// Generate an output for each number from 1 to n
for i from 1 to n
if i is divisible by both 3 and 5
output[i - 1] = "FizzBuzz"
else if i is divisible by 3
output[i - 1] = "Fizz"
else if i is divisible by 5
output[i - 1] = "Buzz"
else
output[i - 1] = convert i to a string
return outputWe are running a single loop and performing constant operations at each iteration. So the time complexity is O(n). We are using constant extra space, so the space complexity is O(1).
Note: The above code works perfectly, but there are some limitations:
Now, the critical question is: How can we solve the Fizz Buzz problem without using the modulo operation? Let's think!
When we explore each number from the start, the word "Fizz" will appear after every cycle of 3. Similarly, the word "Buzz" will appear after every cycle of 5. So, what happens when both words need to be printed together? The answer is simple: "FizzBuzz" will appear after the cycle of 15 because 15 is the lowest number divisible by both 3 and 5. Think!
Using the above insight, let's track the appearance cycles of the words "Fizz" and "Buzz" using two variables: fizzCount and buzzCount. At the start, we initialise both variables to 0 and run a loop from i = 1 to n. At each iteration, we increment fizzCount and buzzCount by 1 and keep track of the cycles of 3 and 5.
Now, there are four scenarios:
fizzBuzzGame(n)
output = array of n strings
fizzCount = 0
buzzCount = 0
// Generate an output for each number from 1 to n
for i from 1 to n
fizzCount = fizzCount + 1
buzzCount = buzzCount + 1
if fizzCount == 3 and buzzCount == 5
output[i - 1] = "FizzBuzz"
fizzCount = 0
buzzCount = 0
else if fizzCount == 3
output[i - 1] = "Fizz"
fizzCount = 0
else if buzzCount == 5
output[i - 1] = "Buzz"
buzzCount = 0
else
output[i - 1] = convert i to a string
return outputWe are running a single loop and doing constant operations at each iteration. So time complexity = O(n). We are using constant extra space, so space complexity = O(1).
In the above solution, we are still using a lot of conditional statements. Now critical question is: Can we reduce the number of conditional statements in the loop? Let's think!
For example, if the problem gets modified from FizzBuzz to FizzBuzzJazz i.e. store "Fizz" if the integer is 3, store "Buzz" if the integer is 5, and store "Jazz" if the integer is 7. If we try to solve this with the previous approach, we need to check several divisibility conditions:
If FizzBuzz mappings increase further, the number of conditional statements will grow in our code. So instead of checking for every possible combination of these conditional statements, we only check for divisibility by given numbers in the problem i.e. 3 and 5. If the number is divisible, we concatenate the corresponding string "Fizz" or "Buzz" to the output[] string.
So for FizzBuzz, we just check for two conditions. Similarly, for FizzBuzzJazz, we would have three conditions to check for divisibility.
Step 1: We define an empty output[] string of size n.
Step 2: Now we run a loop from i = 1 to n. At each iteration:
Step 3: Once the loop is over, we return the output[] string as an output.
fizzBuzzGame(n)
output = array of n strings
// Generate an output for each number from 1 to n
for i from 1 to n
s = ""
// Add "Fizz" if i is divisible by 3
if i is divisible by 3
s = s + "Fizz"
// Add "Buzz" if i is divisible by 5
if i is divisible by 5
s = s + "Buzz"
// Use the number itself if neither condition was met
if s is empty
s = convert i to a string
output[i - 1] = s
return outputWe are running a single loop and doing constant operations at each iteration. So time complexity = O(n). We are using constant extra space, so space complexity = O(1).
When the number of mappings is limited, approach 3 looks good. The critical questions are: What if we need to add too many mappings? What if we need to change the mapping or maybe delete a mapping? Are we going to change the code whenever we have a modification in mappings? So one idea is clear: Having a condition for every mapping is not feasible, or the code might be difficult to maintain.
One idea is to insert all given mappings into a Hash Table in the form of key-value pairs. Here, the number is the key, and the desired output string is the value. For every number i = 1 to n, we go through every entry in the hash table. If the number is divisible by a key, we concatenate the corresponding hash value to the output string for the current number. This way, we can insert or delete mappings from the hash table without changing the code.
Step 1: We insert all mappings in a hash table. For the FizzBuzz problem, the hash table would look something like { (3, 'Fizz'), (5, 'Buzz') }. Similarly, for the FizzBuzzJazz problem, the hash table would look something like { (3, 'Fizz'), (5, 'Buzz'), (7, 'Jazz') }
Step 2: We run a loop from i = 1 to n. For every number i, we iterate over the hash table and check for divisibility with each key. If the number is divisible by a key, we concatenate the corresponding hash value to the output[] string.
Step 3: Finally, we add the resulting string to the output[] string.
fizzBuzzGame(n)
output = array of n strings
fizzBuzz = empty hash table
fizzBuzz.insert(3, "Fizz")
fizzBuzz.insert(5, "Buzz")
// Generate an output for each number from 1 to n
for i from 1 to n
s = ""
// Check the divisors in this order to produce "FizzBuzz"
for key in [3, 5]
if i is divisible by key
s = s + fizzBuzz.get(key)
// Use the number itself if it is divisible by neither 3 nor 5
if s is empty
s = convert i to a string
output[i - 1] = s
return outputThe size of the hash table will be constant because we are storing a constant number of key-value pairs. Space complexity = O(1). At each iteration of the outer loop, we will be doing a constant number of operations. Time complexity = O(n)*O(1) = O(n).
Please write in the message below if you want to share more insight, or if you know some different approaches to solve this problem. Enjoy learning, Enjoy algorithms!