Back to blog
Oct 21, 2024
4 min read

Fizz Buzz

Given an integer n, return a string array answer (1-indexed) where answer[i] is 'FizzBuzz' if i is divisible by 3 and 5, 'Fizz' if divisible by 3, 'Buzz' if divisible by 5, or str(i) otherwise.

Difficulty: Easy | Acceptance: 75.50% | Paid: No Topics: Math, String, Simulation

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.

Examples

Example 1:

Input: n = 3
Output: ["1","2","Fizz"]

Example 2:

Input: n = 5
Output: ["1","2","Fizz","4","Buzz"]

Example 3:

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

Constraints

1 <= n <= 10⁴

Iterative Modulo Check

Intuition The most straightforward approach is to iterate through numbers from 1 to n and check the divisibility conditions for each number individually using the modulo operator.

Steps

  • Loop from 1 to n.
  • Check if the current number is divisible by both 3 and 5 (i.e., 15). If so, append “FizzBuzz”.
  • Else, check if it is divisible by 3. If so, append “Fizz”.
  • Else, check if it is divisible by 5. If so, append “Buzz”.
  • If none of the above, append the string representation of the number.
python
from typing import List

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

Complexity

  • Time: O(n)
  • Space: O(1) (excluding output space)
  • Notes: This approach is simple and readable, but requires checking divisibility multiple times per number.

String Concatenation

Intuition Instead of using multiple conditional branches, we can build the answer string by appending “Fizz” or “Buzz” based on divisibility. If the string remains empty, we append the number itself.

Steps

  • Loop from 1 to n.
  • Initialize an empty string s.
  • If divisible by 3, append “Fizz” to s.
  • If divisible by 5, append “Buzz” to s.
  • If s is still empty, set s to the string representation of the number.
  • Append s to the result list.
python
from typing import List

class Solution:
    def fizzBuzz(self, n: int) -&gt; List[str]:
        ans = []
        for i in range(1, n + 1):
            s = ""
            if i % 3 == 0:
                s += "Fizz"
            if i % 5 == 0:
                s += "Buzz"
            if not s:
                s = str(i)
            ans.append(s)
        return ans

Complexity

  • Time: O(n)
  • Space: O(1) (excluding output space)
  • Notes: This approach is cleaner and more extensible than the modulo check approach, as it avoids nested conditionals.

Hash Map / Precomputed

Intuition To make the solution more generic and extensible (e.g., if we need to handle more divisors like 7 for “Bazz”), we can store the divisor-string pairs in a hash map. We then iterate through the map to build the string for each number.

Steps

  • Create a hash map mapping divisors to their corresponding strings (e.g., 3 -> “Fizz”, 5 -> “Buzz”).
  • Loop from 1 to n.
  • Initialize an empty string s.
  • Iterate through the hash map entries. If the current number is divisible by the key, append the value to s.
  • If s is empty, set s to the string representation of the number.
  • Append s to the result list.
python
from typing import List

class Solution:
    def fizzBuzz(self, n: int) -&gt; List[str]:
        ans = []
        mapping = {3: "Fizz", 5: "Buzz"}
        for i in range(1, n + 1):
            s = ""
            for key in mapping:
                if i % key == 0:
                    s += mapping[key]
            if not s:
                s = str(i)
            ans.append(s)
        return ans

Complexity

  • Time: O(n * k), where k is the number of entries in the hash map (constant for this problem).
  • Space: O(k) for the hash map.
  • Notes: This approach is the most flexible, allowing easy addition of new rules without changing the loop logic.