FizzBuzz
EasyWrite a program that outputs the string representation of numbers from 1 to n. For multiples of 3 output 'Fizz', for multiples of 5 output 'Buzz', and for multiples of both 3 and 5 output 'FizzBuzz'.
Examples
| Input | Output |
|---|---|
| n = 15 | ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"] |
Python Solution
def fizzbuzz(n: int) -> list[str]:
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 resultJavaScript Solution
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(String(i));
}
return result;
}Step-by-Step Explanation
- Iterate from 1 to n.
- Check divisibility by 15 first (both 3 and 5).
- Then check 3 (Fizz) and 5 (Buzz) separately.
- Otherwise append the number as a string.
Complexity Analysis
| Time | O(n) |
| Space | O(1) excluding output |
Tags
MathString
Related Problems
All Problems
Two SumReverse a StringPalindrome CheckBinary SearchReverse Linked ListMerge Two Sorted ArraysValid ParenthesesMaximum Subarray (Kadane's Algorithm)Remove Duplicates from Sorted ArrayNth Fibonacci NumberValid AnagramFirst Unique CharacterClimbing StairsRoman to IntegerBest Time to Buy and Sell StockContains DuplicateMove ZeroesIntersection of Two ArraysLongest Common Prefix