Fizz Buzz easy
Problem Statement
Given an integer n
, return a string array answer
(1-indexed) where:
answer[i] == "FizzBuzz"
ifi
is divisible by 3 and 5.answer[i] == "Fizz"
ifi
is divisible by 3.answer[i] == "Buzz"
ifi
is divisible by 5.answer[i] == i
(as a string) if none of the above conditions are true.
Example 1
Input: n = 3 Output: ["1","2","Fizz"]
Example 2
Input: n = 5 Output: ["1","2","Fizz","4","Buzz"]
Steps
- Initialization: Create an empty array
answer
to store the results. - Iteration: Iterate from 1 to
n
(inclusive). - Divisibility Check: For each number
i
, check its divisibility by 3 and 5 using the modulo operator (%
). - Conditional Logic: Based on the divisibility checks, assign the appropriate string to
answer[i-1]
(because arrays are 0-indexed). - Return: Return the
answer
array.
Explanation
The solution uses a simple iterative approach. For each number from 1 to n
, we check its divisibility by 3 and 5. If it's divisible by both, we add "FizzBuzz". If only by 3, we add "Fizz". If only by 5, we add "Buzz". Otherwise, we add the number itself as a string. The if-else if-else
structure ensures that the conditions are checked in the correct order to handle cases where a number is divisible by both 3 and 5.
Code
function fizzBuzz(n: number): string[] {
const answer: string[] = [];
for (let i = 1; i <= n; i++) {
if (i % 3 === 0 && i % 5 === 0) {
answer.push("FizzBuzz");
} else if (i % 3 === 0) {
answer.push("Fizz");
} else if (i % 5 === 0) {
answer.push("Buzz");
} else {
answer.push(i.toString());
}
}
return answer;
}
Complexity
- Time Complexity: O(n) - The code iterates through the numbers from 1 to n once.
- Space Complexity: O(n) - The
answer
array can store up to n strings.