Hide sidebar

Fizz Buzz

Fizz Buzz

MathString
EasyLeetCode #412
5 min

Problem Statement

Given an integer n, return a string array answer (1-indexed) where:

  • answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
  • answer[i] == "Fizz" if i is divisible by 3.
  • answer[i] == "Buzz" if i is divisible by 5.
  • answer[i] == i (as a string) if none of the above conditions are true.

Example

Example 1:

Input: n = 15

For n = 15:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

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

Solution (Simple Iteration)

The FizzBuzz problem is a classic programming task that tests basic loop and conditional logic. The approach is to iterate from 1 to n and apply a set of rules.

Algorithm Steps

  • Initialize an empty list or array to store the results.
  • Loop from 1 to n.
  • For each number, first check if it's divisible by both 3 and 5. If so, add "FizzBuzz" to your list.
  • If not, check if it's divisible by 3. If so, add "Fizz".
  • If not, check if it's divisible by 5. If so, add "Buzz".
  • If none of the above are true, add the number itself (as a string) to the list.
  • After the loop finishes, return the list of results.

Current Number (i)

-

Result Array

[]

Start with n = 15.
Fizz Buzz Solution

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