Taro Logo

Fizz Buzz

Easy
Apple logo
Apple
Topics:
ArraysStrings

Given an integer n, return a string array answer (1-indexed) where:

  1. answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
  2. answer[i] == "Fizz" if i is divisible by 3.
  3. answer[i] == "Buzz" if i is divisible by 5.
  4. answer[i] == i (as a string) if none of the above conditions are true.

For example:

  • If n = 3, the output should be ["1","2","Fizz"].
  • If n = 5, the output should be ["1","2","Fizz","4","Buzz"].
  • If n = 15, the output should be ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"].

Write a function to solve this problem, keeping in mind that 1 <= n <= 10^4.

Solution


Let's start with a straightforward, brute-force approach to solve the FizzBuzz problem.

Naive Approach

The most basic solution involves iterating from 1 to n and checking divisibility by 3 and 5 for each number. This will clearly demonstrate the logic and constraints.

def fizzBuzz_naive(n):
    answer = []
    for i in range(1, n + 1):
        if i % 3 == 0 and i % 5 == 0:
            answer.append("FizzBuzz")
        elif i % 3 == 0:
            answer.append("Fizz")
        elif i % 5 == 0:
            answer.append("Buzz")
        else:
            answer.append(str(i))
    return answer

Big(O) Analysis

  • Time Complexity: O(n), because we iterate through each number from 1 to n.
  • Space Complexity: O(n), as we store the output in a list of size n.

Optimal Approach

While the naive approach is already quite efficient, we can optimize it slightly by reducing redundant calculations. However, the primary goal is readability and maintainability, as the performance gains will be minimal for the given constraints.

An optimal approach maintains the same O(n) time complexity but focuses on cleaner code.

def fizzBuzz_optimal(n):
    answer = []
    for i in range(1, n + 1):
        result = ""
        if i % 3 == 0:
            result += "Fizz"
        if i % 5 == 0:
            result += "Buzz"
        if not result:
            result = str(i)
        answer.append(result)
    return answer

Big(O) Analysis

  • Time Complexity: O(n), still iterating through each number from 1 to n.
  • Space Complexity: O(n), as we store the output in a list of size n.

Edge Cases

  • n = 0 or n < 0: The problem states that 1 <= n <= 10^4, so we don't need to handle cases where n is zero or negative. However, in a real-world scenario, adding a check for invalid input would be a good practice.
  • Large n: Although n can be up to 10,000, the algorithm's linear time complexity ensures it will still perform efficiently.

Conclusion

The optimal solution provides a slightly cleaner and more readable approach while maintaining the same time and space complexity as the naive solution. The key is to ensure the code is easy to understand and maintain, especially in collaborative environments.