Python 0412.py
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
result = []
for i in range(1, n+1):
add = ""
if i % 3 == 0:
add += "Fizz"
if i % 5 == 0:
add += "Buzz"
if add == "":
add = str(i)
result.append(add)
return result
Difficulty
and has an acceptance rate of about 76% (2+ million submissions).
Typical patterns to solve this problem:
- Math
- Simulation
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a class Solution with a single method fizzBuzz. The method receives an integer n and returns a list of strings representing the classic FizzBuzz sequence from 1 through n. For each integer in the range, the method decides whether to emit "Fizz" (multiples of 3), "Buzz" (multiples of 5), "FizzBuzz" (multiples of both 3 and 5), or the number itself as a string. The result is accumulated in a list that is returned at the end of the method.
Core Logic
The algorithm begins by creating an empty list called result. This list will hold the final sequence of strings.
result = []
A for loop iterates over the inclusive range from 1 to n. The loop variable i represents the current integer being processed.
for i in range(1, n+1):
Inside the loop, a temporary string variable add is initialized to an empty string. This variable is used to build the appropriate output for the current integer.
add = ""
Two conditional checks examine the divisibility of i. The first check appends "Fizz" to add when i is divisible by 3.
if i % 3 == 0:
add += "Fizz"
The second check appends "Buzz" to add when i is divisible by 5. Because the string concatenation uses +=, the two checks naturally combine to produce "FizzBuzz" when both conditions are true.
if i % 5 == 0:
add += "Buzz"
After the divisibility tests, a final condition determines whether any text was added. If add remains empty, the integer does not satisfy either multiple condition, and the algorithm substitutes the numeric value converted to a string.
if add == "":
add = str(i)
The computed string is then appended to the result list.
result.append(add)
When the loop completes, the method returns the populated list.
return result
Edge Cases Handled
When n is zero or negative, the range(1, n+1) construct yields an empty sequence, causing the loop body to be skipped entirely. Consequently, result remains an empty list, which is returned. This behavior gracefully handles non-positive inputs without raising errors.
When i is a multiple of both 3 and 5 (i.e., a multiple of 15), the two separate conditional blocks each contribute their respective substrings. The first block adds "Fizz" and the second adds "Buzz", resulting in the combined string "FizzBuzz". This demonstrates that the implementation correctly handles the overlapping case without requiring an explicit combined condition.
When i is a multiple of only one of the factors, the corresponding conditional block adds the appropriate word while the other block does nothing, leaving add with either "Fizz" or "Buzz" as required.
When i is not a multiple of either factor, the final check replaces the empty add with the string representation of i. This ensures that every integer in the range contributes exactly one element to the output list.
Performance Optimizations
The code avoids unnecessary data structures by building each output string directly in a local variable and appending it to the result list in a single step. The use of string concatenation with += for the two possible words is efficient because the number of concatenations per iteration is bounded by two, and Python’s internal string handling optimizes short-lived concatenations.
The loop iterates exactly n times, and each iteration performs a constant amount of work: two modulus operations, at most two string concatenations, a simple equality check, and a list append. By keeping the work per iteration minimal and avoiding nested loops or additional passes over the data, the implementation achieves a streamlined execution path.
The decision to convert the integer to a string only when necessary (i.e., when add is empty) reduces the number of str conversions, which can be relatively costly compared to simple arithmetic checks. This conditional conversion contributes to a modest performance gain, especially for large values of n.
Overall, the method delivers the FizzBuzz sequence with a clear, linear flow and minimal overhead, leveraging Python’s built-in constructs for concise and efficient computation.
ELI5 - Simplified Explanation
Imagine counting toys in a big box. This code plays a fun game while counting from one up to a number you choose. It looks at every number one at a time. If the number can be shared perfectly by three, it says Fizz. If the number can be shared perfectly by five, it says Buzz. If a number is special and can be shared by both three and five, it says FizzBuzz. If the number does not fit those rules, it just keeps the number as it is. It puts each of these answers into a list, almost like putting stickers into an album, until it finishes counting everything.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||||
| WalkCCC | C++ | Python | Java | ||||||||||
| leetcode.ca | C++ | Python | JS | Java | Go | PHP | |||||||
| LeetcodeHelp | C++ | Python | Java | ||||||||||
| Progiez | C++ | Python | Java | ||||||||||
| github | AdelDaniel | Dart | |||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++ | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| DimitrisJim | C | ||||||||||||
| everthis | JS | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fengvyi | C++ | ||||||||||||
| fsq | Python | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JS | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| Krazune | C# | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| muhammadfarhankt | Go | ||||||||||||
| qiyuangong | C++ | ||||||||||||
| ruoru | Rust | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| varunu28 | Java | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ | ||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||
| WalkCCC | C++, Python, Java | ||||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, PHP, Python | ||||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||||
| Progiez | C++, Java, Python | ||||||||||||
| AdelDaniel | Dart | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++, C++ | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| DimitrisJim | C | ||||||||||||
| everthis | JavaScript | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fengvyi | C++ | ||||||||||||
| fsq | Python | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JavaScript | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| Krazune | C# | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| muhammadfarhankt | Go | ||||||||||||
| qiyuangong | C++ | ||||||||||||
| ruoru | Rust | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| varunu28 | Java | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 342: Power of Four
- problem 344: Reverse String
- problem 345: Reverse Vowels of a String
- problem 349: Intersection of Two Arrays
- problem 350: Intersection of Two Arrays II
- problem 387: First Unique Character in a String
- problem 414: Third Maximum Number
- problem 434: Number of Segments in a String
- problem 448: Find All Numbers Disappeared in an Array
- problem 485: Max Consecutive Ones
- problem 504: Base 7
- problem 507: Perfect Number
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality