https://leetcode.com/problems/fizz-buzz

This is very classical and old interview question and I think already a lot was discussed. Here is my solution, where we use simple approach: we iterate over numbers, check for each number what we need to add and add it. Also, for more universality I use words = ["Fizz", "Buzz"], mods = [3,5] and k=2. What we do next is just iterate over numbers and for each number check if it is divisible by 3 and by 5.

Complexity: time complexity is O(n), more precisely, we do 2 division checks for each number and then add result to res. It can be optimized, if we do not check each number, but firstly create array [1,2,3,...,n], and then traverse only numbers divisible by 3 in one pass and numbers divisible by 5 in second pass. Space complexity is O(n) as well.

class Solution:
    def fizzBuzz(self, n):
        words, mods = ["Fizz", "Buzz"], [3, 5]
        k, res = 2, []
        for i in range(1, n+1):
            current_str = ""
            for j in range(k):
                if i%mods[j] == 0: current_str += words[j]
                    
            if not current_str:
                res.append(str(i))
            else:
                res.append(current_str)
                
        return res

If you like the solution, you can upvote it on leetcode discussion section: Problem 0412