Статья пока доступна только на английском.
Problem Description
You are given an integer n.
Write a function that takes n and returns an array of strings answer built according to the following rules:
answer[i] == "FizzBuzz"ifiis divisible by both 3 and 5;answer[i] == "Fizz"ifiis divisible by 3 only;answer[i] == "Buzz"ifiis divisible by 5 only;answer[i] == iin all other cases.
Constraints
The value of n is in the range from 1 to 104.
Examples
Input: 3
Answer: ["1","2","Fizz"]
Solution
To solve the problem, we run a loop from 1 to n and check 4 mutually exclusive conditions on each iteration.
If a condition holds, we append the corresponding string to the result array.
typescript
export const fizzBuzz = (n: number): string[] => {
const res: string[] = [];
for (let i = 1; i <= n; i++) {
if (i % 3 == 0 && i % 5 == 0) {
res.push('FizzBuzz');
} else if (i % 3 == 0) {
res.push('Fizz');
} else if (i % 5 == 0) {
res.push('Buzz');
} else {
res.push(String(i));
}
}
return res;
};Complexity Analysis
Time Complexity
The time complexity is linear: O(n), since we iterate from 1 to n.
Space Complexity
The space complexity is constant: O(1), since we don't create any additional variables besides the answer.