Write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

Example:

Input: 15

Output:

[
   "1",
   "2",
   "Fizz",
   "4",
   "Buzz",
   "Fizz",
   "7",
   "8",
   "Fizz",
   "Buzz",
   "11",
   "Fizz",
   "13",
   "14",
   "FizzBuzz"
]

Solution

from typing import List

class Solution:
    def fizzBuzz(self, n: int) -> List[str]:
        res = []

        for i in range(1, n + 1):
            newStr = str(i)

            if i % 15 == 0:
                newStr = 'FizzBuzz'
            elif i % 3 == 0:
                newStr = 'Fizz'
            elif i % 5 == 0:
                newStr = 'Buzz'

            res.append(newStr)

        return res

Test Cases

test = Solution()
answer = test.fizzBuzz(3)
assert answer == [
    '1',
    '2',
    'Fizz'
]

answer = test.fizzBuzz(5)
assert answer == [
    '1',
    '2',
    'Fizz',
    '4',
    'Buzz'
]

answer = test.fizzBuzz(15)
assert answer == [
    '1',
    '2',
    'Fizz',
    '4',
    'Buzz',
    'Fizz',
    '7',
    '8',
    'Fizz',
    'Buzz',
    '11',
    'Fizz',
    '13',
    '14',
    'FizzBuzz'
]

print('All Passed!')

Big O Analysis

Space Complexity: O(1)

Time Complexity: O(N)