Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

412. Fizz Buzz - Leetcode Solution

Code Implementation

class Solution:
    def fizzBuzz(self, n: int) -> List[str]:
        result = []
        for i in range(1, n+1):
            if i % 3 == 0 and i % 5 == 0:
                result.append("FizzBuzz")
            elif i % 3 == 0:
                result.append("Fizz")
            elif i % 5 == 0:
                result.append("Buzz")
            else:
                result.append(str(i))
        return result
      
class Solution {
public:
    vector<string> fizzBuzz(int n) {
        vector<string> result;
        for (int i = 1; i <= n; ++i) {
            if (i % 3 == 0 && i % 5 == 0)
                result.push_back("FizzBuzz");
            else if (i % 3 == 0)
                result.push_back("Fizz");
            else if (i % 5 == 0)
                result.push_back("Buzz");
            else
                result.push_back(to_string(i));
        }
        return result;
    }
};
      
class Solution {
    public List<String> fizzBuzz(int n) {
        List<String> result = new ArrayList<>();
        for (int i = 1; i <= n; i++) {
            if (i % 3 == 0 && i % 5 == 0) {
                result.add("FizzBuzz");
            } else if (i % 3 == 0) {
                result.add("Fizz");
            } else if (i % 5 == 0) {
                result.add("Buzz");
            } else {
                result.add(Integer.toString(i));
            }
        }
        return result;
    }
}
      
var fizzBuzz = function(n) {
    let result = [];
    for (let i = 1; i <= n; i++) {
        if (i % 3 === 0 && i % 5 === 0) {
            result.push("FizzBuzz");
        } else if (i % 3 === 0) {
            result.push("Fizz");
        } else if (i % 5 === 0) {
            result.push("Buzz");
        } else {
            result.push(i.toString());
        }
    }
    return result;
};
      

Problem Description

The Fizz Buzz problem asks you to write a function that takes an integer n and returns a list of strings representing the numbers from 1 to n. However, for multiples of 3, you should output "Fizz" instead of the number, and for multiples of 5, output "Buzz". For numbers which are multiples of both 3 and 5, output "FizzBuzz". For all other numbers, output the number itself as a string.

  • Input: An integer n (1 ≤ n ≤ 104).
  • Output: A list of strings, one for each number from 1 to n, following the Fizz Buzz rules.
  • Each number is checked individually, and the output for each position depends only on that number.

Thought Process

The Fizz Buzz problem is a classic programming exercise that tests your ability to use conditional logic and loops. The straightforward way to approach the problem is to iterate through each number from 1 to n and decide what string to output based on whether the number is divisible by 3, 5, or both.

Initially, one might think to check divisibility for each number using the modulo operator. The challenge is to ensure that numbers divisible by both 3 and 5 are correctly labeled as "FizzBuzz", rather than just "Fizz" or "Buzz". This means the check for both 3 and 5 must come before checking for 3 or 5 individually.

While there are ways to optimize or generalize the solution, the problem is simple enough that a direct, readable approach is preferred. The main focus is clarity and correctness.

Solution Approach

  • Step 1: Initialize an empty list.
    Create a list (or array) to store the resulting strings.
  • Step 2: Loop from 1 to n.
    For each number i in this range:
    • If i is divisible by both 3 and 5 (i.e., i % 15 == 0), append "FizzBuzz" to the list.
    • Else if i is divisible by 3, append "Fizz".
    • Else if i is divisible by 5, append "Buzz".
    • Else, append the string representation of i.
  • Step 3: Return the list.
    After the loop, return the completed list of strings.

This solution uses a simple for loop and basic conditional statements. The order of the checks is important: always check for divisibility by both 3 and 5 first, to avoid missing "FizzBuzz".

Example Walkthrough

Let's walk through the process with n = 15:

  • i = 1: Not divisible by 3 or 5. Output "1".
  • i = 2: Not divisible by 3 or 5. Output "2".
  • i = 3: Divisible by 3. Output "Fizz".
  • i = 4: Not divisible by 3 or 5. Output "4".
  • i = 5: Divisible by 5. Output "Buzz".
  • i = 6: Divisible by 3. Output "Fizz".
  • i = 7: Not divisible by 3 or 5. Output "7".
  • i = 8: Not divisible by 3 or 5. Output "8".
  • i = 9: Divisible by 3. Output "Fizz".
  • i = 10: Divisible by 5. Output "Buzz".
  • i = 11: Not divisible by 3 or 5. Output "11".
  • i = 12: Divisible by 3. Output "Fizz".
  • i = 13: Not divisible by 3 or 5. Output "13".
  • i = 14: Not divisible by 3 or 5. Output "14".
  • i = 15: Divisible by both 3 and 5. Output "FizzBuzz".

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

Time and Space Complexity

  • Brute-Force Approach:
    The brute-force and optimal approach are the same for this problem. For each number from 1 to n, we perform a constant number of operations (checking divisibility and appending to a list).
    • Time Complexity: O(n), because we loop once through all numbers from 1 to n.
    • Space Complexity: O(n), as we store one string for each number in the output list.
  • Why?
    There is no way to avoid examining each number at least once, so O(n) is optimal for both time and space.

Summary

The Fizz Buzz problem is a simple exercise in using loops and conditional statements. By checking divisibility in the correct order, we can produce the required output efficiently and clearly. The solution is direct, readable, and optimal, requiring only a single pass through the numbers and straightforward logic. This makes Fizz Buzz a great introductory problem for practicing control flow and basic programming skills.