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;
}
function fizzBuzz(n: number): string[] {
const out: string[] = [];
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;
}
def fizz_buzz(n: int) -> list[str]:
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
<?php
function fizzBuzz(int $n): array
{
$out = [];
for ($i = 1; $i <= $n; $i++) {
$out[] = match (true) {
$i % 15 === 0 => 'FizzBuzz',
$i % 3 === 0 => 'Fizz',
$i % 5 === 0 => 'Buzz',
default => (string) $i,
};
}
return $out;
}
class Solution {
public String[] fizzBuzz(int n) {
String[] out = new String[n];
for (int i = 1; i <= n; i++) {
out[i - 1] = i % 15 == 0 ? "FizzBuzz" : i % 3 == 0 ? "Fizz" : i % 5 == 0 ? "Buzz" : String.valueOf(i);
}
return out;
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy