Fizz Buzz
Problem
Return a string array of length n where the i-th entry (1-indexed) is "FizzBuzz" if i is divisible by 15, "Fizz" if divisible by 3, "Buzz" if divisible by 5, otherwise the number itself.
n = 5["1","2","Fizz","4","Buzz"]def fizz_buzz(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
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;
}
class Solution {
public List<String> fizzBuzz(int n) {
List<String> out = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (i % 15 == 0) out.add("FizzBuzz");
else if (i % 3 == 0) out.add("Fizz");
else if (i % 5 == 0) out.add("Buzz");
else out.add(String.valueOf(i));
}
return out;
}
}
vector<string> fizzBuzz(int n) {
vector<string> out;
for (int i = 1; i <= n; i++) {
if (i % 15 == 0) out.push_back("FizzBuzz");
else if (i % 3 == 0) out.push_back("Fizz");
else if (i % 5 == 0) out.push_back("Buzz");
else out.push_back(to_string(i));
}
return out;
}
Explanation
This is the classic warm-up problem. We just walk through the numbers 1 to n and decide what each one should turn into, using simple divisibility checks.
The one detail that matters is the order of the checks. A number divisible by both 3 and 5 is also divisible by 15, so we must test i % 15 == 0 first. If we checked 3 or 5 before 15, we would wrongly output "Fizz" or "Buzz" instead of "FizzBuzz".
For each i we ask: divisible by 15 → "FizzBuzz"; else by 3 → "Fizz"; else by 5 → "Buzz"; otherwise just the number as a string. Because these are elif branches, only the first matching rule fires.
Example with n = 5: 1 and 2 hit no rule, so they stay "1" and "2"; 3 is divisible by 3 giving "Fizz"; 4 stays "4"; 5 is divisible by 5 giving "Buzz". The result is ["1","2","Fizz","4","Buzz"].
We touch each number once and append one string, so the work is O(n).