DSA Factory
Free lessonsProgramming basics · Stage 9 · Mastery · Step 1

Fizz and buzz

Count up, and say a word instead of the number when a rule fits. About 12 minutes.

No label this time

From here on, the steps don't tell you which idea to use. A problem arrives with no label, and you decide which tools to reach for. Before you start, ask: what am I repeating, what choices do I make each time, and what do I build up?

A small hint for this one. Some numbers fit more than one rule, such as 15, which is a multiple of 3 and of 5. When one number fits two rules, the order you ask the questions in decides the answer.

Before coding: what repeats, what is chosen, and what is built up?
Counting from 1 to 15
1
0
2
1
3
2
4
3
5
4
6
5
7
6
8
7
9
8
10
9
11
10
12
11
13
12
14
13
15
14
i
i
1
word
1

1 is not a multiple of 3 or 5, so the word is the number itself, as text.

Move 1 of 5
Quick check

Why should the question for numbers that are multiples of both 3 and 5 come first?

  1. AOtherwise 15 would match the Fizz question first, and the answer would be wrong
  2. BIt makes the code run faster
  3. CThe order doesn't matter
Show the answer

Otherwise 15 would match the Fizz question first, and the answer would be wrong. The first true question wins. 15 is a multiple of 3, so it would stop at Fizz and never reach the both-rule.

Your problem

Fizz buzz

Return a list with one text for each number from 1 to n. If the number is a multiple of both 3 and 5, the text is "FizzBuzz". If it is a multiple of 3 only, the text is "Fizz". If it is a multiple of 5 only, the text is "Buzz". Otherwise the text is the number itself, written as text.

Example
n = 5 → ["1", "2", "Fizz", "4", "Buzz"]

0 ≤ n ≤ 1,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding