Skip to main content

FizzBuzz

Print numbers 1 to n, replacing multiples of 3 with 'Fizz', multiples of 5 with 'Buzz', and multiples of both with 'FizzBuzz'.

Problem Overview

  • The Ultimate Pattern Recognition Test
FizzBuzz is the quintessential programming interview question that tests your ability to handle multiple conditions elegantly. Count from 1 to n, but with a twist - numbers divisible by specific values get replaced with words!

🧠 The Logic Challenge:

  • Divisible by 3: Replace with "Fizz"
  • Divisible by 5: Replace with "Buzz"
  • Divisible by both: Replace with "FizzBuzz" (order matters!)
  • Everything else: Keep the original number as string
  • Three Implementation Strategies:
  • Standard If-Else: Clear, readable, checks 15 first for efficiency
  • String Concatenation: Elegant approach that builds the result dynamically
  • Functional One-Liner: Array.from + ternary operators for concise code
  • Real-World Applications:
  • Rule Engines: Business logic with multiple conditional branches
  • Data Transformation: Converting numeric data based on business rules
  • Game Logic: Implementing scoring systems with special conditions
  • Report Generation: Formatting data with conditional text replacement
💡 Learning Value:
  • Conditional logic and operator precedence
  • Modulo arithmetic for divisibility testing
  • String vs numeric data handling
  • Code clarity vs cleverness trade-offs

Concepts

LoopsConditionalsModular Arithmetic

Complexity Analysis

Time:O(n)
Space:O(n)
Performance Notes:

- Time: O(n) - must process each number once - Space: O(n) - output array grows with input size

Solutions

fizzBuzz

Time: O(n) | Space: O(n)
export function fizzBuzz(n: number): string[] {
  if (!Number.isInteger(n) || n < 1) throw new Error("Input must be a positive integer");
  const result: string[] = [];
  for (let i = 1; i <= n; i++) {
    if (i % 15 === 0) result.push("FizzBuzz");
    else if (i % 3 === 0) result.push("Fizz");
    else if (i % 5 === 0) result.push("Buzz");
    else result.push(i.toString());
  }
  return result;
}

Examples & Test Cases

#1Classic FizzBuzz up to 15
Input:15
Output:[ "1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz" ]
#2Small example
Input:5
Output:[ "1", "2", "Fizz", "4", "Buzz" ]
#3Invalid input
Input:0
Output:{}