🏷️ 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

ConceptWhy It Matters
Modulo operatorBasic arithmetic
Condition orderLogic trap awareness
Clean codeReadability

⚠️ 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

Scroll to Top