Published on

fizzBuzz

Authors
  • Name
    Twitter

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.

  • Constraints:

    1. 1 <= n <= 104
  • Examples:

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

Solutions

Approach 1: Naive Approach

class Solution(object):
    def fizzBuzz(self, n: int) -> List[str]:
        # Create an empty list to store the output
        output = []
        # Loop through the numbers from 1 to n
        for i in range(1, n+1):
            # If the number is divisible by 3 and 5
            if i % 3 == 0 and i % 5 == 0:
                # Append "FizzBuzz" to the output list
                output.append("FizzBuzz")
            # If the number is divisible by 3
            elif i % 3 == 0:
                # Append "Fizz" to the output list
                output.append("Fizz")
            # If the number is divisible by 5
            elif i % 5 == 0:
                # Append "Buzz" to the output list
                output.append("Buzz")
            # If the number is not divisible by 3 or 5
            else:
                # Append the number as a string to the output list
                output.append(str(i))
        # Return the output list
        return output

Approach 2: String Concatenation

class Solution(object):
    def fizzBuzz(self, n: int) -> List[str]:
        output = []
        for i in range(1, n + 1):
            result = ""
            if i % 3 == 0:
                result = result + "Fizz"
            if i % 5 == 0:
                result = result + "Buzz"
            if not result:
                result = str(i)
            output.append(result)
        return output

Approach 3: Hash it!

class Solution(object):
    def fizzBuzz(self, n: int) -> List[str]:
        # Create a hash table to store the numbers and their mappings
        hash_table = {3: "Fizz", 5: "Buzz"}
        output = []
        for i in range(1, n + 1):
            result = ""
            for key in hash_table.keys():
                if i % key == 0:
                    result = result + hash_table[key]
            if not result:
                result = str(i)
            output.append(result)
        return output

References

  1. LeetCode - fizzBuzz
  2. Tom Scott - https://youtu.be/QPZ0pIK_wsc?si=leE6hoM7AL50xaTL