Fizz Buzz

Easy

Topics
MathStringSimulation

Given an integer n, return a string array answer of length n where, for each i from 1 to n:

  • answer[i-1] == "FizzBuzz" if i is divisible by both 3 and 5;
  • answer[i-1] == "Fizz" if i is divisible by 3;
  • answer[i-1] == "Buzz" if i is divisible by 5;
  • answer[i-1] == i as a string otherwise.

Example 1

12Fizz
divisible by 3
One chip per value from 1 to 3. A value divisible by both 3 and 5 is labelled FizzBuzz rather than one or the other, which is the whole content of the problem. Everything else keeps its own number, as a string.
Each chip is one entry of the answer array.
Input:  n = 3
Output: ["1","2","Fizz"]

Example 2

12Fizz4Buzz
divisible by 3divisible by 5
Input:  n = 5
Output: ["1","2","Fizz","4","Buzz"]

Example 3

12Fizz4BuzzFizz78FizzBuzz11Fizz1314FizzBuzz
divisible by 3divisible by 5divisible by both
Input:  n = 15
Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]

Constraints

  • 1 <= n <= 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

The only thing to get right is the order of the tests. Divisible by 15 has to be checked before divisible by 3 or 5, because 15 satisfies all three and only the combined label is correct.

Writing it as "divisible by 3 and by 5" rather than "divisible by 15" keeps the rule readable and generalises if a third divisor is ever added.

Approach

  1. Walk i from 1 to n.
  2. Build the label by concatenation: start empty, append "Fizz" when i % 3 == 0, then append "Buzz" when i % 5 == 0.
  3. If the label is still empty, use the decimal form of i.
  4. That ordering produces "FizzBuzz" for multiples of 15 with no separate case.

Walkthrough

n = 5

i=1  3? no  5? no  -> "1"
i=2  3? no  5? no  -> "2"
i=3  3? yes 5? no  -> "Fizz"
i=4  3? no  5? no  -> "4"
i=5  3? no  5? yes -> "Buzz"

Complexity

  • Time — O(n): one label per value, each built in constant time.
  • Space — O(n): the output array; nothing else is retained.

Common Pitfalls

  • Checking i % 3 first and returning immediately mislabels every multiple of 15.
  • The values are strings, including the plain numbers — a mixed array of numbers and strings is not the required shape.

Full Solution — all languages

class Solution:
    def fizzBuzz(self, n):
        out = []
        for i in range(1, n + 1):
            if i % 15 == 0:
                out.append("FizzBuzz")
            elif i % 3 == 0:
                out.append("Fizz")
            elif i % 5 == 0:
                out.append("Buzz")
            else:
                out.append(str(i))
        return out
SensAI
Beta
Tap the mic to stop voice mode