412. Fizz Buzz | LeetCode | Solution

It’s a classic programming problem and a very beginner type of problem. Here is the link to the problem. See the explanation in LeetCode first. And try to understand the problem.

First, we will be given a number n as input. We have to store each number from 1 to n in an array as a string. But remember three things before the store.

  • If a number is divisible by 3, we will store Fizz instead of that number.
  • If a number is divisible by 5, we will store Buzz instead of that number.
  • If a number is divisible by both 3 and 5, we will store FizzBuzz instead of that number.

In our coding part, first, we will create an empty list (a list is equivalent to an array). Then we will iterate through the number from 1 to n. In our loop body, first, we will check the current number is divisible by 3 and 5 or not. If the condition is true, we will append Fizzbuzz in our list instead of the current number.

If the first condition is false, we will go to the second condition and so on. The code of those conditions is self-explanatory.

If every condition is false, we will append the number in string format.

Let’s see the full code below.

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

If you submit the code in LeetCode, it will be accepted.

Scroll to Top