You are tasked with writing an algorithm to solve the “Fizz Buzz” 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.answer[i] == "Buzz"
if i
is divisible by 5.answer[i] == i
(as a string) if none of the above conditions are true.Input: n = 15
Output: ["1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz"]
n
: What is the range of the input integer n
?
1 <= n <= 10^4
.n
is the smallest possible value (i.e., n = 1
)?
n
.The strategy is straightforward:
1
to n
, and for each number:
answer
to store the result.1
to n
(both inclusive).i
in this range, use conditional checks to determine the appropriate string to append to the list.answer
at the end.def fizzBuzz(n: int):
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
# Example Usage
n = 15
print(fizzBuzz(n)) # Output: ["1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz"]
1
to n
, performing constant-time operations for each number.
n
elements.This concludes the solution for the Fizz Buzz problem using a simple and efficient algorithm.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?