π·οΈ Category: Algorithms / Logic | π― Difficulty:
Easy| π₯ Frequency: β β β β β
π Problem Statement
For numbers 1 to n:
- PrintΒ βFizzBuzzβΒ if divisible by both 3 and 5
- PrintΒ βFizzβΒ if divisible by 3
- PrintΒ βBuzzβΒ if divisible by 5
- Otherwise print theΒ number
π₯ Input β n = 15
π€ Output β [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz",
"Buzz", 11, "Fizz", 13, 14, "FizzBuzz"]
π§ What the Interviewer is Testing
| Concept | Why It Matters |
|---|---|
| Modulo operator | Basic arithmetic |
| Condition order | Logic trap awareness |
| Clean code | Readability |
β οΈ Classic trap: Check divisible by 15 first, then 3, then 5. If you check 3 first, βFizzBuzzβ never prints correctly.
π‘ Approach
Check order matters:
1οΈβ£ n % 15 == 0 β "FizzBuzz" β MUST be first
2οΈβ£ n % 3 == 0 β "Fizz"
3οΈβ£ n % 5 == 0 β "Buzz"
4οΈβ£ else β str(n)
β Optimal Solution
def fizzbuzz(n: int) -> list:
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
# ββ Test Cases βββββββββββββββββββββββββββββββββ
print(fizzbuzz(15))
# β
['1','2','Fizz','4','Buzz','Fizz','7','8',
# 'Fizz','Buzz','11','Fizz','13','14','FizzBuzz']
π Pythonic One-liner Version
def fizzbuzz_clean(n: int) -> list:
return [
"FizzBuzz" if i % 15 == 0 else
"Fizz" if i % 3 == 0 else
"Buzz" if i % 5 == 0 else
str(i)
for i in range(1, n + 1)
]
π Complexity Analysis
βββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ
β Time O(n) β Single loop through 1 to n β
β Space O(n) β Output list of n elements β
βββββββββββββββ΄βββββββββββββββββββββββββββββββββββββ
π€ How to Explain in the Interview
βI check divisibility by 15 first β that handles the FizzBuzz case. Then 3 for Fizz, 5 for Buzz, otherwise the number itself. The order is critical β checking 3 or 5 before 15 would break the FizzBuzz output.β
π Common Follow-up Questions
Q1 β Make it extensible for any rules?
def fizzbuzz_generic(n: int, rules: dict) -> list:
# rules = {3: "Fizz", 5: "Buzz", 7: "Boom"}
result = []
for i in range(1, n + 1):
word = ''.join(v for k, v in sorted(rules.items()) if i % k == 0)
result.append(word if word else str(i))
return result
π Set 1 of 4 β Python Interview Prep Series β devprepguide.com
