FizzBuzz

Easy TimeO(n) SpaceO(n)

Given a number n, return the numbers from 1 to n written out as text, except that every multiple of 3 becomes "Fizz", every multiple of 5 becomes "Buzz", and any number that is a multiple of both becomes "FizzBuzz".

Examples

Example 1

Input
n = 15
Output
["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
Fifteen answers come back, and only the last of them is a multiple of both.

Example 2

Input
n = 5
Output
["1","2","Fizz","4","Buzz"]
Nothing here is a multiple of both, so "FizzBuzz" never appears.

The Code

function fizzBuzz(n) {
  const out = [];
  for (let i = 1; i <= n; i++) {
    if (i % 15 === 0) out.push("FizzBuzz");
    else if (i % 3 === 0) out.push("Fizz");
    else if (i % 5 === 0) out.push("Buzz");
    else out.push(String(i));
  }
  return out;
}
fizzBuzz(15);
Done

The first 11 calls, of 17. This one does not fit on a page.

Step through fizzBuzz(15) call by call

Explanation

Each number meets the strictest rule first — both, then 3, then 5 — and is written out as itself only when all three miss.

  1. 1

    At i = 1: i % 15 is not 0, i % 3 is not 0 and i % 5 is not 0, so the last branch runs and the number itself is pushed.

    1
    0
    2
    1
    3
    2
    4
    3
    5
    4

    i=1

    out.push("1")

  2. 2

    At i = 3: i % 15 is 3, so that test misses — but i % 3 is 0, and the second branch runs.

    1
    0
    2
    1
    3
    2

    i=3

    out.push("Fizz")

  3. 3

    At i = 5: the first two tests miss and i % 5 is 0.

    Fizz
    0
    4
    1
    5
    2

    i=5

    out.push("Buzz")

  4. 4

    At i = 15: i % 15 is 0 and the first branch runs. Had the test for 3 come first, it would have matched too and this would have been pushed as "Fizz".

    15
    0
    both
    1

    i=15

    out.push("FizzBuzz")