Write a function `fizzBuzz(n)` that returns an array from 1 to n where multiples of 3 are "Fizz", multiples of 5 are "Buzz", multiples of both are "FizzBuzz", and others are the number itself.
Problem Statement
Examples
Input: n = 5
Output: [1, 2, "Fizz", 4, "Buzz"]
Explanation: 3 is replaced with "Fizz" and 5 with "Buzz".
Input: n = 15
Output: [..., 14, "FizzBuzz"]
Explanation: Multiples of both 3 and 5 are replaced with "FizzBuzz".
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
To solve FizzBuzz, we consider the execution characteristics of JavaScript engines. Write a function `fizzBuzz(n)` that returns an array from 1 to n where multiples of 3 are "Fizz", multiples of 5 are "Buzz", multiples of both are "FizzBuzz", and others are the number itself. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.
Step-by-Step Approach
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (use the modulo operator (%) to check divisibility).
- Implement Logic: Handle state and transformations efficiently (check divisibility by 15 first (both 3 and 5), then 3, then 5).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function fizzBuzz(n) {
const result = [];
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);
}
return result;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Empty or boundary inputs (empty arrays, strings, zero length).
- Type checks and unexpected values (e.g.
null,undefined, negative numbers). - Closure preservation and memory isolation between separate invocations.