Skip to content
Problem 412 · LeetCode 412(opens in a new tab)

Fizz Buzz

EasyMath

You are given a positive integer n. Return a list of n strings, one for each number from 1 to n in order.

For a number divisible by 3 write "Fizz", for one divisible by 5 write "Buzz", and for one divisible by both write "FizzBuzz". Any other number is written as its own digits, such as "7".

Example 1

Input:  n = 6
Output: ["1","2","Fizz","4","Buzz","Fizz"]
Why:    3 and 6 are multiples of 3, and 5 is a multiple of 5
1 more example and the constraints

Example 2

Input:  n = 1
Output: ["1"]
Why:    1 is not divisible by 3 or 5, so it stays a number

Constraints

  • 1 ≤ n ≤ 10,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Check 15 firstO(n)
  2. Build the wordO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 10,000Verdict
Check 15 firstO(n)
Fine; order of checks is a trap
Build the wordO(n)
Best; easy to extend

n = the last number. Both do the same amount of work; the second is easier to get right and to change.

Edge cases to test

  • n = 1. The answer is just ["1"].
  • n below 15. No "FizzBuzz" appears at all, only Fizz and Buzz.
  • Multiples of 15. 15, 30, 45 must give "FizzBuzz", not "Fizz".
  • Largest n. 10,000 strings; a single pass is easily fast enough.

Common mistakes

  • Checking 3 before 15 in an if/else chain, so 15 comes out as "Fizz".
  • Starting the loop at 0 or stopping at n − 1, which shifts every answer by one.
  • Returning numbers instead of strings, such as 7 rather than "7".

How to talk through it

  1. 1Clarify. Is the list 1-indexed, from 1 through n? Should plain numbers come back as strings?
  2. 2Name the trap. A multiple of 15 matches both rules, so an if/else chain must test it first.
  3. 3Build the word. Append "Fizz" and "Buzz" separately and fall back to the number; no ordering trap.
  4. 4Mention extension. New rules become (divisor, word) pairs in a list.
  5. 5Test out loud. Run 1, 3, 5 and 15 through the loop.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?