FizzBuzz – Solution & Complexity

Solution Walkthrough

  1. Step 1: Understand the Replacement Rules

    • For every number from 1 through n, return one string.
    • Multiples of 3 become Fizz, multiples of 5 become Buzz.
    • Multiples of both must become FizzBuzz, not just one of the two words.
  2. Step 2: Check the Most Specific Case First

    • A number divisible by both 3 and 5 is divisible by 15.
    • Check this case before checking only 3 or only 5.
    • Otherwise 15 would incorrectly be labeled as just Fizz or just Buzz.
    if num % 15 == 0:
        result.append("FizzBuzz")
  3. Step 3: Loop Through the Range

    • Use range(1, n + 1) because the sequence includes both endpoints: 1 and n.
    • Append the correct string for each number.
    • Convert normal numbers with str(num).
    for num in range(1, n + 1):
        if num % 15 == 0:
            result.append("FizzBuzz")
        elif num % 3 == 0:
            result.append("Fizz")
  4. Step 4: Handle Input Robustly

    • The problem describes n as an integer, but JSON input can sometimes provide numeric-looking values as strings.
    • Converting with int(n) makes the function tolerant of either form.
    • The output remains a list of strings.
  5. Step 5: Complete Solution and Complexity

    • The final solution makes one pass from 1 to n and applies the divisibility rules.
    • Time complexity is O(n).
    • Space complexity is O(n) for the returned list.
    def fizz_buzz(n: int) -> list[str]:
        n = int(n)
        result = []
    
        for num in range(1, n + 1):
            if num % 15 == 0:
                result.append("FizzBuzz")
            elif num % 3 == 0:
                result.append("Fizz")
            elif num % 5 == 0:
                result.append("Buzz")
            else:
                result.append(str(num))
    
        return result

FAQ