Sponsored
Sponsored
This approach iterates through numbers from 1 to n and applies conditional logic using modulus operations to determine if a number should be represented as "Fizz", "Buzz", or "FizzBuzz". If none of these conditions are met, the number itself is returned as a string.
Time Complexity: O(n)
as we iterate through each number from 1 to n
once.
Space Complexity: O(n)
for the output array.
1var fizzBuzz = function(n) {
2 let result = [];
3 for (let i = 1; i <= n; i++) {
4 if (i % 3 === 0 && i % 5 === 0) {
5 result.push("FizzBuzz");
6 } else if (i % 3 === 0) {
7 result.push("Fizz");
8 } else if (i % 5 === 0) {
9 result.push("Buzz");
10 } else {
11 result.push(i.toString());
12 }
13 }
14 return result;
15};
16
JavaScript implementation uses an array for the results and a for
loop to perform the necessary checks. Strings are pushed to the array after evaluating conditions for each number.
This approach uses a hash map to store possible outputs, simplifying conditional checks. By mapping integers to their respective Fizz
or Buzz
values, we consolidate decision logic, reducing redundancy in the code.
Time Complexity: O(n)
, since each element is evaluated once.
Space Complexity: O(n)
due to storage for result strings.
1#include <vector>
#include <string>
std::vector<std::string> fizzBuzz(int n) {
const std::string values[4] = { "", "Fizz", "Buzz", "FizzBuzz" };
std::vector<std::string> result(n);
for (int i = 1; i <= n; ++i) {
int index = (i % 15 == 0) ? 3 : (i % 3 == 0) ? 1 : (i % 5 == 0) ? 2 : 0;
result[i - 1] = (index == 0) ? std::to_string(i) : values[index];
}
return result;
}
The C++ version employs an array of strings and refers to it directly. By determining the index based on divisibility checks, the correct string is selected with minimal conditional checks.