Fizz Buzz — LeetCode 412 Python Solution

EasyMathStringSimulation
Problem
#412
Reading time
2 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(n), where n is the integer given in the problem
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview