LeetCode Problem Workspace

Fizz Buzz

Generate a list from 1 to n replacing multiples of 3 with Fizz, 5 with Buzz, and both with FizzBuzz efficiently.

category

3

Topics

code_blocks

6

Code langs

hub

3

Related

Practice Focus

Easy · Math plus String

bolt

Answer-first summary

Generate a list from 1 to n replacing multiples of 3 with Fizz, 5 with Buzz, and both with FizzBuzz efficiently.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for Math plus String

Try AiBox Copilotarrow_forward

The Fizz Buzz problem requires iterating from 1 to n and converting numbers into strings with rules for multiples of 3, 5, or both. The optimal approach uses a simple loop with conditional checks and string concatenation. GhostInterview focuses on producing correct output arrays while avoiding common mistakes like incorrect indexing or redundant checks.

Problem Statement

Given an integer n, return a 1-indexed string array where each element follows these rules: replace numbers divisible by 3 with "Fizz", numbers divisible by 5 with "Buzz", and numbers divisible by both 3 and 5 with "FizzBuzz". All other numbers should appear as their string representation. The solution should work efficiently up to the constraint limits.

For example, for n = 3, the output should be ["1","2","Fizz"]. For n = 5, output is ["1","2","Fizz","4","Buzz"]. For n = 15, output includes "FizzBuzz" at multiples of 15, showing proper string concatenation for combined multiples. This problem tests the Math plus String pattern and attention to iteration and modular arithmetic.

Examples

Example 1

Input: n = 3

Output: ["1","2","Fizz"]

Example details omitted.

Example 2

Input: n = 5

Output: ["1","2","Fizz","4","Buzz"]

Example details omitted.

Example 3

Input: n = 15

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

Example details omitted.

Constraints

  • 1 <= n <= 104

Solution Approach

Iterative Loop with Conditional Checks

Loop from 1 to n, check divisibility by 3 and 5 using modulo, and build the string accordingly. Append 'Fizz' for multiples of 3, 'Buzz' for multiples of 5, and 'FizzBuzz' when both conditions hold. This approach ensures correct mapping while avoiding off-by-one errors.

Single Concatenation String Strategy

Instead of nested ifs, concatenate 'Fizz' and 'Buzz' based on divisibility, then use the number as string if the result is empty. This reduces conditional complexity and directly encodes the Math plus String pattern for easy readability and maintenance.

Array Preallocation for Efficiency

Preallocate the result array to size n and assign values by index to avoid dynamic resizing overhead. This keeps the solution within expected time and space bounds for large n and highlights efficient handling of array operations in simulation patterns.

Complexity Analysis

Metric Value
Time Depends on the final approach
Space Depends on the final approach

Time complexity is O(n) since each number is checked once for divisibility and string concatenation is constant time. Space complexity is O(n) for the output array, with no extra data structures required beyond simple string variables.

What Interviewers Usually Probe

  • Checks for modulo operations versus combined conditional logic.
  • Watches for correct 1-indexed output versus off-by-one errors.
  • Notes clarity in string concatenation instead of multiple nested conditions.

Common Pitfalls or Variants

Common pitfalls

  • Using zero-based indexing incorrectly, leading to off-by-one results.
  • Checking divisibility in the wrong order, causing 'FizzBuzz' to be replaced by 'Fizz' or 'Buzz'.
  • Appending numbers instead of converting to strings for non-multiples.

Follow-up variants

  • Return the result as a comma-separated string instead of an array.
  • Modify divisibility rules to use different multiples like 2 and 7 for custom patterns.
  • Handle large n with streaming output to reduce memory usage.

FAQ

What is the main pattern in Fizz Buzz that needs attention?

The key pattern is Math plus String: using modulo to detect multiples of 3, 5, or both, and converting results into strings accordingly.

Can I optimize Fizz Buzz beyond O(n)?

No, each number from 1 to n must be processed at least once to apply the replacement rules, so O(n) is the expected time complexity.

Why is the order of divisibility checks important?

Checking 3 and 5 separately before the combined check can overwrite 'FizzBuzz', causing incorrect results. Combined check should be prioritized or handled with concatenation.

How does GhostInterview help avoid off-by-one mistakes?

It ensures all loops and array accesses are correctly 1-indexed and alerts users when standard zero-based loops might cause errors.

Are there space optimizations for Fizz Buzz?

The main space use is the output array of size n; preallocation avoids dynamic resizing, and streaming approaches can reduce peak memory for very large n.

terminal

Solution

Solution 1: Simulation

We iterate through each integer from 1 to $n$. For each integer, we check whether it is a multiple of both 3 and 5, or just a multiple of 3, or just a multiple of 5. Based on the check result, we add the corresponding string to the answer array.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
    def fizzBuzz(self, n: int) -> 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
Fizz Buzz Solution: Math plus String | LeetCode #412 Easy