Write a program that, given an integer n, prints numbers from 1 to n each on a new line, replacing multiples of 3 with "Fizz", multiples of 5 with "Buzz", and multiples of both 3 and 5 with "FizzBuzz".
What the interviewer wants to learn
- Your ability to translate a simple specification into correct code.
- How you think about edge cases, input validation, and performance.
- Whether you can explain the algorithm clearly and justify its complexity.
How to structure your answer
1. Restate the problem in your own words to confirm understanding.
2. Outline the algorithm step‑by‑step (loop, condition checks).
3. Mention time and space complexity.
4. Show a concise implementation (preferably in a common language).
5. Highlight any edge‑case handling (e.g., n ≤ 0).
Example answer
“Sure, the task is to print numbers from 1 to n, but replace multiples of 3 with ‘Fizz’, multiples of 5 with ‘Buzz’, and multiples of both with ‘FizzBuzz’. I’d solve it with a single for‑loop that iterates from 1 to n. For each i I’d build the output string: if i is divisible by 3 I append ‘Fizz’, if it’s divisible by 5 I append ‘Buzz’. If the string stays empty, I just print i itself. This runs in O(n) time and O(1) extra space because we only keep a few variables. Here’s a quick Python snippet:
def fizzbuzz(n):
if n <= 0:
return # nothing to print
for i in range(1, n + 1):
out = ''
if i % 3 == 0:
out += 'Fizz'
if i % 5 == 0:
out += 'Buzz'
print(out or i)
The modulo operations are constant‑time, so overall the algorithm is linear in n, which is optimal for this problem. I also added a guard for non‑positive n to avoid an empty output.”
Mistakes to avoid
- Skipping the clarification step; assume the interviewer’s intent without confirming.
- Using nested loops or extra data structures that increase complexity unnecessarily.
- Forgetting to handle n ≤ 0 or non‑integer inputs, which can cause runtime errors.
- Printing the whole sequence at once (e.g., building a large list) which inflates space usage.
- Over‑explaining trivial code; keep the explanation concise and focused on the core logic.