Fizz Buzz (LeetCode 412): Solution and Explanation

Easy
Math
String
Simulation

Return the strings for 1 through n, replacing multiples of 3 with "Fizz", multiples of 5 with "Buzz" and multiples of both with "FizzBuzz". Every other number is written as itself.

Intuition

Each entry depends only on its own index, so a single loop from 1 to n that decides one string per number is all the structure needed.

The only real decision is the order of the tests. A number divisible by both 3 and 5 also passes the test for 3 alone, so if you check 3 first, 15 comes out as "Fizz". Checking the combined case first (divisible by 15, since 3 and 5 share no factor) removes that trap.

Laid out in rows of 15, the answer shows the whole problem at a glance: columns 3, 6, 9 and 12 are always Fizz, columns 5 and 10 are always Buzz, column 15 is always FizzBuzz, and the other eight columns are plain numbers. The pattern has period 15 because that is the least common multiple of 3 and 5.

Approach: Single pass, combined case first

  1. Create an empty list answer.
  2. For each i from 1 to n, check i % 15 == 0 first and append "FizzBuzz".
  3. Otherwise, if i % 3 == 0 append "Fizz"; otherwise if i % 5 == 0 append "Buzz".
  4. Otherwise append i converted to a string.
  5. Return answer.

Step-by-step example

n = 15
  1. i = 1 and 2 have non-zero remainders for both 3 and 5, so append "1" and "2".
  2. i = 3: 3 % 3 = 0, append "Fizz". i = 4: append "4". i = 5: 5 % 5 = 0, append "Buzz".
  3. i = 6 and 9 and 12 are multiples of 3: "Fizz". i = 10 is a multiple of 5: "Buzz". 7, 8, 11, 13 and 14 stay numbers.
  4. i = 15: 15 % 15 = 0, so the first test fires and appends "FizzBuzz" before the single tests are reached.
  5. Return the 15 strings.

Code: Python, Java, C++

1class Solution:
2    def fizzBuzz(self, n: int) -> List[str]:
3        answer = []
4        for i in range(1, n + 1):
5            if i % 15 == 0:
6                answer.append("FizzBuzz")
7            elif i % 3 == 0:
8                answer.append("Fizz")
9            elif i % 5 == 0:
10                answer.append("Buzz")
11            else:
12                answer.append(str(i))
13        return answer
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One iteration per number with a constant number of modulo checks.

Space

O(1)

Not counting the returned list of n strings, only the loop variable is used.

Other approaches

String concatenation (time O(n), space O(1))

Start with an empty string, add "Fizz" if i % 3 == 0 and "Buzz" if i % 5 == 0, and use the number when the string is still empty. It extends cleanly to more rules (for example "Jazz" for 7) without a combinatorial number of branches.

Counters instead of modulo (time O(n), space O(1))

Keep two counters that count up to 3 and 5 and reset, and emit Fizz or Buzz when they hit their limit. It avoids the modulo operator, which only matters on hardware where division is expensive.

Common mistakes

  • Testing i % 3 or i % 5 before the combined case, which turns 15, 30 and 45 into "Fizz".
  • Looping from 0 to n - 1. The answer is 1-indexed, so it must start at "1" and end at the string for n.
  • Returning integers for the plain entries. Every element must be a string.

Frequently asked questions

Why test divisibility by 15 instead of by 3 and by 5 separately?

Because 3 and 5 share no common factor, a number is divisible by both exactly when it is divisible by 15. Writing i % 3 == 0 and i % 5 == 0 is equally correct; 15 is just shorter.

How many FizzBuzz entries does the answer contain?

floor(n / 15). There are floor(n / 3) - floor(n / 15) Fizz entries and floor(n / 5) - floor(n / 15) Buzz entries.

Can it be faster than O(n)?

No, the output itself has n strings, so producing it takes at least linear time.