Fizz Buzz

Fizz Buzz

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:

  • If the number is divisible by both 3 and 5, append "FizzBuzz".
  • Otherwise if it is divisible by 3, append "Fizz".
  • Otherwise if it is divisible by 5, append "Buzz".
  • Otherwise, append the number as a string.
fizzBuzz(n)

Examples

fizzBuzz(5)   // → ["1", "2", "Fizz", "4", "Buzz"]
fizzBuzz(3)   // → ["1", "2", "Fizz"]
fizzBuzz(1)   // → ["1"]

Walkthrough

Thinking it through

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 trap in the conditions

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.

Building the approach

  1. Prepare an empty list for your results.
  2. For each number 1 through n: is it divisible by 15? If yes, record "FizzBuzz."
  3. If not, is it divisible by 3? If yes, record "Fizz."
  4. If not, is it divisible by 5? If yes, record "Buzz."
  5. If none of those hit, record the number itself as text.
  6. Return the full list.

Why this is efficient and why ordering is the whole game

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.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.