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#
This C solution defines a constant array storing potential word outputs for Fizz
, Buzz
, and FizzBuzz
. Indexes based on divisibility determine which string to select, reducing the number of branch conditions.