Fizz Buzz — Day 55(Python)

Annamariya Tharayil
2 min readJan 7, 2021
Photo by Nick Fewings on Unsplash

Today’s question is somewhat easy. I thought since we were learning dynamic programming for quite some time, It was good to have a change and learn something easy. Let us look into the question.

412. Fizz Buzz

Write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three, it should output “Fizz” instead of the number, and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

Example:

n = 15,Return:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"
]

To solve this problem we start a loop from 1, run it up to the required number. Each time we check if the current number is divisible by 15, 3, 5. Wait, why did I say we should check if the current number is divisible by 15? The question states the number should be divisible by 3 and 5 too. Since 15 is divisible by both 3 and 5, we check if the current number is divisible by 15.

Let us look into the code snippet.

class FizzBuzzer:
def fizzBuzz(self, n: int) -> List[str]:
output = []
for i in range(1, n+1):
if i%15 == 0:
output.append("FizzBuzz")
elif i%3 == 0:
output.append("Fizz")
elif i%5 == 0:
output.append("Buzz")
else:
output.append(str(i))
return output

Complexity analysis.

Time Complexity

We are running a loop from 1 to N, hence, the time complexity is O(N).

Space Complexity.

We are not using any extra data structure, hence the space complexity is O(1).

--

--