Write a function that takes a positive integer n and returns a slice of strings
following the Fizz Buzz pattern. For each number from 1 to n:
"FizzBuzz"."Fizz"."Buzz".fizzBuzz(n)
fizzBuzz(5) // → ["1", "2", "Fizz", "4", "Buzz"]
fizzBuzz(3) // → ["1", "2", "Fizz"]
fizzBuzz(1) // → ["1"]
This one isn't about algorithmic cleverness — it's about ordering your conditions so they don't step on each other. Walk through every number from 1 to n and decide which of four outputs it gets. Since each number's answer doesn't depend on any other number, this is naturally a single pass.
The four rules overlap: "divisible by both 3 and 5" is a special case of both "divisible by 3" and "divisible by 5." If you check 3 and 5 separately without handling the overlap, a number like 15 gets caught by the first check it hits and never reaches the other rule — or gets mislabeled.
The fix: check the most specific case first. "Divisible by both 3 and 5" is the same as "divisible by 15," since 3 and 5 share no common factors. Check that first, and only numbers that fail it ever fall through to the individual 3-only or 5-only checks.
Each number needs at most three simple remainder checks, so the total work is directly proportional to n — one pass, constant work per number, giving O(n) time and O(n) space for the output. There's no cleverer trick here; the whole challenge is testing the most specific overlapping condition before the broader ones, so it never gets shadowed. That ordering discipline shows up anywhere multiple conditions can be true at once.
def fizz_buzz(n):
result = []
for i in range(1, n + 1):
if i % 15 == 0:
result.append("FizzBuzz")
elif i % 3 == 0:
result.append("Fizz")
elif i % 5 == 0:
result.append("Buzz")
else:
result.append(str(i))
return result
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.