#412
Fizz Buzz
Easy Strings & List
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
For numbers 1 to n, produce a list of strings: "FizzBuzz" for multiples of both 3 and 5, "Fizz" for multiples of 3, "Buzz" for multiples of 5, and the number itself otherwise.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: label each number 1..n by whether 3 and/or 5 divide it.
Why this works: the % operator tests divisibility. Checking 15 first makes sure "FizzBuzz" wins over plain "Fizz".
Example: n = 6
1 → "1", 2 → "2", 3 → "Fizz", 4 → "4", 5 → "Buzz", 6 → "Fizz"✦Hints open one at a time
Check the "both" case first, or build the string piece by piece.
Use a List<String> and String.valueOf(i) for plain numbers.
↗Approach
Loop from 1 to n, use the modulo operator to test divisibility and add the right string to an ArrayList.
</>Solution (Java)
import java.util.*;
class Solution {
public List<String> fizzBuzz(int n) {
List<String> ans = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (i % 15 == 0) ans.add("FizzBuzz"); // divisible by both
else if (i % 3 == 0) ans.add("Fizz");
else if (i % 5 == 0) ans.add("Buzz");
else ans.add(String.valueOf(i));
}
return ans;
}
}
!Common mistake
Checking i % 3 before i % 15, so 15 prints "Fizz" instead of "FizzBuzz".
Complexity
- Time: O(n).
- Space: O(n) for the output list.
