Coding problem · Easy · Basics

FizzBuzz

Easy Algorithms & data structures

Return a list of strings for the numbers 1 to n:

  • "FizzBuzz" if the number is divisible by both 3 and 5,
  • "Fizz" if divisible by 3, "Buzz" if divisible by 5,
  • otherwise the number itself as a string.

Example 1

Input: n = 5
Output: ["1","2","Fizz","4","Buzz"]

Example 2

Input: n = 15
Output: [..., "14", "FizzBuzz"]

Hints

Hint 1

Check divisibility with the remainder operator %.

Hint 2

Check 'divisible by 15' (both) before the single checks.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n) · Space O(n)

The only trap is order: test for 15 (or both 3 and 5) first, otherwise a multiple of 15 returns just Fizz.

Reference solution

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;
}

Was this page helpful?