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
.answer[i] == "Buzz"
if i
is divisible by 5
.answer[i] == i
(as a string) if none of the above conditions are true.For example:
n = 3
, the output should be ["1","2","Fizz"]
.n = 5
, the output should be ["1","2","Fizz","4","Buzz"]
.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
.
Let's start with a straightforward, brute-force approach to solve the FizzBuzz problem.
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
n
.n
.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
n
.n
.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.n
can be up to 10,000, the algorithm's linear time complexity ensures it will still perform efficiently.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.