Fizz Buzz
Easy · Math & Geometry · Explanation and code example
Independent Divisibility Rules
How it works
For each integer, append Fizz when divisible by three and Buzz when divisible by five. These conditions are independent, so multiples of fifteen receive both words. When neither applies, use the integer’s decimal representation.
Steps
- Visit integers from one through n.
- Append each matching word in Fizz-then-Buzz order.
- Use the number when the constructed string is empty.
Complexity
- Time: O(n + L) for L returned characters.
- Space: O(L) output and O(1) extra workspace.
Things to watch for
- Using else between the rules would miss FizzBuzz.
- Start at one.
- Return strings rather than printing them.
Python code example
class Solution:
def fizzBuzz(self, n: int) -> list[str]:
d = {3: 'Fizz', 5: 'Buzz'}
return [''.join([d[k] for k in d if i % k == 0]) or str(i) for i in range(1, n + 1)]
C++ code example
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> ans;
for (int i = 1; i <= n; ++i) {
string s;
if (i % 3 == 0)
s += "Fizz";
if (i % 5 == 0)
s += "Buzz";
ans.push_back(s.empty() ? to_string(i) : s);
}
return ans;
}
};
Source and license
Explanation by LC Tracker. Code adapted from walkccc / Peng-Yu Chen · MIT license. Node types are supplied by LeetCode where needed.