easyArrayArrays & Hashing

FizzBuzz

easyTime: O(n)Space: O(n)

The shape of the problem

For each number 1..n, print a label that depends on divisibility by 3 and 5. The order of the checks controls the output because "FizzBuzz" must win when both rules match.

Signals to notice

divisibility rulesstring concatenationpriority order

Brute force first

Separate `if` branches for each of the four cases: divisible by 15, by 3 only, by 5 only, neither. Works, but duplicates the 3- and 5-checks and is easy to misorder.

The key insight

Divisible-by-15 is just divisible-by-3 AND divisible-by-5. If you concatenate instead of branching, the combined case falls out for free.

Trace it on n=5

i=1  → not %3, not %5  → "1"
i=2  → not %3, not %5  → "2"
i=3  → %3             → "Fizz"
i=4  → not %3, not %5  → "4"
i=5  → %5             → "Buzz"

What must stay true

Output length equals n, and the label at position i depends only on (i mod 3, i mod 5).

Shape of the loop

for i in 1..n:
  s = ""
  if i % 3 == 0: s += "Fizz"
  if i % 5 == 0: s += "Buzz"
  print(s or str(i))

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Writing `if i%3==0: print Fizz elif i%5==0: print Buzz elif i%15==0: print FizzBuzz`. The FizzBuzz branch is unreachable because `i%3==0` catches every multiple of 15 first.

Arrays & Hashing Pattern