Solution

You must have played FizzBuzz as kids. FizzBuzz charm never gets old. And so here we are looking at how you can take on one step at a time and impress your interviewer with a better and neat approach to solve this problem.

Approach 1: Naive Approach

Intuition

The moment you hear of FizzBuzz you think whether the number is divisible by 3, 5 or both.

Algorithm

Initialize an empty answer list.

Iterate on the numbers from .

For every number, if it is divisible by both 3 and 5, add FizzBuzz to the answer list.

Else, Check if the number is divisible by 3, add Fizz.

Else, Check if the number is divisible by 5, add Buzz.

Else, add the number.

Complexity Analysis

Time Complexity:

Space Complexity:

Approach 2: String Concatenation

Intuition

This approach won't reduce the asymptotic complexity, but proves to be a neater solution when FizzBuzz comes with a twist.
What if FizzBuzz is now FizzBuzzJazz i.e.

3 ---> "Fizz" , 5 ---> "Buzz", 7 ---> "Jazz"

If you try to solve this with the previous approach the program would have too many conditions to check:

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.

This way if the FizzBuzz mappings increase, the conditions would grow exponentially in your program.

Algorithm

Instead of checking for every combination of these conditions, check for divisibility by given numbers i.e. 3, 5 as given in the problem. If the number is divisible, concatenate the corresponding string mapping Fizz or Buzz to the current answer string.