Fizz Buzz
You're given an integer n. Return a list of n strings describing the numbers 1 through n in order, so answer[0] is for 1. A number divisible by both 3 and 5 becomes "FizzBuzz", one divisible by 3 only becomes "Fizz", one divisible by 5 only becomes "Buzz", and any other number is written as itself, like "7".
Examples
n = 3 returns ["1","2","Fizz"]
1 and 2 aren't divisible by 3 or 5, so they're written as numbers. 3 is divisible by 3, so it becomes "Fizz".
n = 5 returns ["1","2","Fizz","4","Buzz"]
4 is written as "4", and 5 is divisible by 5 but not 3, so it becomes "Buzz".
n = 15 returns ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
15 is the first number divisible by both 3 and 5, so it becomes "FizzBuzz". Along the way, 6, 9 and 12 become "Fizz" and 10 becomes "Buzz".
Constraints
- 1 <= n <= 10^4
Hints
Each number's label depends only on whether 3 and 5 divide it. Which case has to be checked before the others?
Use the modulo operator in an if / else-if chain, testing the most specific condition first.
For i from 1 to n: if i % 15 == 0 append "FizzBuzz", else if i % 3 == 0 append "Fizz", else if i % 5 == 0 append "Buzz", else append str(i). Return the list.
Drill This: Your Approach First
Approach
Loop i from 1 to n and pick each entry with the modulo operator. Test i % 15 == 0 first, since a number divisible by both 3 and 5 is divisible by 15, then i % 3, then i % 5, and fall back to str(i). The order matters because the chain stops at the first match. Beyond the output list itself, only the loop counter is used.
Time
O(n)
Space
O(1)
Pitfall
Solutions
class Solution {
public List<String> fizzBuzz(int n) {
List<String> out = new ArrayList<>(n);
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(Integer.toString(i));
}
return out;
}
}class Solution:
def fizzBuzz(self, n: int):
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