Fizz Buzz — LeetCode 412 Python Solution
- Problem
- #412
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an integer n, return a string array answer (1-indexed) where: answer[i] == "FizzBuzz" if i is divisible by 3 and 5. answer[i] == "Fizz" if i is divisible by 3.
Example
- Input
- n = 3
- Output
- ["1","2","Fizz"]
Python solution
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
ans = []
for i in range(1, n + 1):
if i % 15 == 0:
ans.append('FizzBuzz')
elif i % 3 == 0:
ans.append('Fizz')
elif i % 5 == 0:
ans.append('Buzz')
else:
ans.append(str(i))
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the integer given in the problem |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 412. Fizz Buzz is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 412. Fizz Buzz?
- LeetCode 412. Fizz Buzz is rated Easy on LeetCode.
- What is the time complexity of LeetCode 412. Fizz Buzz?
- The Python solution on this page runs in O(n), where n is the integer given in the problem.
- What is the space complexity of LeetCode 412. Fizz Buzz?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 412. Fizz Buzz cover?
- LeetCode 412. Fizz Buzz is tagged Math, String and Simulation on LeetCode.