Fizz Buzz Problem

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.

Let’s understand the problem!

This game is played in a group, where players take turns to say the next number in a sequence, counting one at a time.

  • If the number is divisible by 3, the player must say “Fizz” instead of the number itself.
  • If the number is divisible by 5, the player must say “Buzz”.
  • If the number is divisible by 3 and 5, the player must say “FizzBuzz”.

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:

  • output[i] = "FizzBuzz" if i is divisible by 3 and 5.
  • output[i] = "Fizz" if i is divisible by 3.
  • output[i] = "Buzz" if i is divisible by 5.
  • output[i] = "i" if none of the above conditions are true.

Example

Input: n = 15

Output: ["1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz"]

Discussed solution approaches

  • Using modulus operation
  • Without using modulus operations
  • Using string concatenation
  • Using hash table

Using modulus operation

Solution idea

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.

Solution steps

  1. We define an empty output[] string of size n.
  2. We run a loop from 1 to n and check divisibility by 3 or 5 or both.
  3. For i is divisible by both 3 and 5, we add the string "FizzBuzz" at ith index of the output string. 
  4. Else, if integer i is divisible by 3, we add "Fizz".
  5. Else, if integer i is divisible by 5, we add "Buzz".
  6. Else, we add the string value of integer i.

Solution pseudocode

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 output

Solution analysis

We 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:

  1. The statements i % 3 == 0 and i % 5 == 0 are repeated twice.
  2. At a low level, the modulo is a division operation that can be costly in terms of performance, especially for large integers.
  3. It uses a lot of messy conditional statements, which are hard to maintain when the number of divisibility conditions increases in the problem.

Without using modulus operations

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.

  • We reset fizzCount = 0 when fizzCount == 3. 
  • We reset buzzCount = 0 when buzzCount == 5. 

Now, there are four scenarios:

  1. fizzCount != 3 and buzzCount != 5: We store the string value of number i in the output string.
  2. fizzCount == 3 and buzzCount != 5: We store the word "Fizz" in the output string and set fizzCount = 0.
  3. fizzCount != 3 and buzzCount == 5: We store the word "Buzz" in the output string and set buzzCount = 0.
  4. fizzCount == 3 and buzzCount == 5: We store the word "FizzBuzz" in the output string and set both buzzCount and fizzCount equal to 0.

Solution pseudocode

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 output

Solution analysis

We 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).

Using string concatenation

Solution idea

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:

  • Divisible by 3, divisible by 5, divisible by 7
  • Divisible by 3 and 5, divisible by 3 and 7, divisible by 7 and 3
  • Divisible by 3 and 5 and 7, Not divisible by 3 or 5 or 7.

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.

Solution steps

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:

  • We start by defining an empty string s. 
  • If i is divisible by 3, we add “Fizz” at the end of the empty string s. 
  • Similarly, if i is divisible by 5, we add “Buzz” at the end of the empty string s. 
  • Now we check whether string s is empty or not. If yes, we store the string value of integer i in the empty string s. 
  • Finally, we store the value of s at output[i].

Step 3: Once the loop is over, we return the output[] string as an output.

Solution pseudocode

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 output

Solution analysis

We 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).

Using hash table

Solution idea

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.

Solution steps

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.

Solution pseudocode

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 output

Solution analysis

The 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).

Critical ideas to think!

  • How will the time and space complexity of the above approaches change when integer-to-string mapping increases in the problem?
  • In approach 1, can we check the divisibility by 15 to print the "FizzBuzz" instead of checking the divisibility by both 3 and 5?
  • Can we come up with some other approaches to solve this problem?
  • The hash table works as an unordered dictionary which does not preserve the order of keys. Can we use the ordered dictionary or BST to solve this problem? What would be the time complexity? Is it better than the hash table approach?
  • Instead of the hash table, can we use the ordered list of (divisor, string)?
  • Explore the library implementation of dictionaries in various programming languages. Do they have some extra capabilities to preserve the insertion order of elements?
  • Explore the several variations of the FizzBuzz problem.
  • Just for fun :) Write the worst but the working implementation of Fizz Buzz that you can think of!

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!

More from EnjoyAlgorithms

Self-paced Courses and Blogs