You are given an integer n. Your task:
Return a list of strings from 1 to n following these rules:
- If the number is divisible by 3 → output
"Fizz" - If divisible by 5 → output
"Buzz" - If divisible by both 3 and 5 → output
"FizzBuzz" - Otherwise → output the number itself as a string
Example:
Input: n = 5 Output: ["1","2","Fizz","4","Buzz"]
Another example:
Input: n = 15
Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz",
"11","Fizz","13","14","FizzBuzz"]
Problem Understanding
Important details:
- Output type is a list of strings, not integers
- Order must be from 1 to n
- Multiples of both 3 and 5 must output
"FizzBuzz"— this condition must be checked first - No extra formatting or spacing
- n can be as large as 10⁴, so a simple loop is sufficient
Logic Explained in Simple English
Here’s the simplest way to think about it:
- Loop from 1 up to n
- For each number:
- First check if it’s divisible by 3 and 5
- If yes, add
"FizzBuzz"
- If yes, add
- Else if divisible by 3
- Add
"Fizz"
- Add
- Else if divisible by 5
- Add
"Buzz"
- Add
- Else
- Convert number to string and add it
- First check if it’s divisible by 3 and 5
Why check 3 and 5 first?
Because if we check 3 first, then multiples like 15 would be labeled "Fizz" before "FizzBuzz", producing the wrong output.
This ensures correct priority and correctness.
Step-by-Step Approach
- Create an empty list of strings
- Loop i from 1 to n
- For each i:
- If i % 15 == 0 → add “FizzBuzz”
- Else if i % 3 == 0 → add “Fizz”
- Else if i % 5 == 0 → add “Buzz”
- Else → add String.valueOf(i)
- Return the list
Java Implementation
class Solution {
public List<String> fizzBuzz(int n) {
List<String> result = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (i % 15 == 0) {
result.add("FizzBuzz");
} else if (i % 3 == 0) {
result.add("Fizz");
} else if (i % 5 == 0) {
result.add("Buzz");
} else {
result.add(String.valueOf(i));
}
}
return result;
}
}
Dry Run Example
Input:
n = 10
Loop and output:
1 → “1” (not divisible by 3 or 5)
2 → “2”
3 → “Fizz”
4 → “4”
5 → “Buzz”
6 → “Fizz”
7 → “7”
8 → “8”
9 → “Fizz”
10 → “Buzz”
Final output:
["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz"]
Time and Space Complexity
Time Complexity
O(n)
One loop through numbers 1 to n
Space Complexity
O(n)
Result list stores n strings
Common Mistakes and How to Avoid Them
Mistake 1: Checking divisible by 3 before checking divisible by both
This incorrectly labels 15 as "Fizz"
Mistake 2: Returning integers instead of strings
Every entry must be a string
Mistake 3: Using concatenation logic incorrectly
This problem has fixed category outputs, not combinations like "FizzBuzzFizz"
Mistake 4: Off-by-one in loop bounds
Must loop from 1 through n inclusive
Mistake 5: Using slow string operations unnecessarily
Simple string literals are enough
