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.
1def fizzBuzz(n):
2 result = []
3 for i in range(1, n + 1):
4 if i % 3 == 0 and i % 5 == 0:
5 result.append("FizzBuzz")
6 elif i % 3 == 0:
7 result.append("Fizz")
8 elif i % 5 == 0:
9 result.append("Buzz")
10 else:
11 result.append(str(i))
12 return result
13
The Python solution utilizes a list to track results. A for
loop checks divisibility and either appends Fizz
, Buzz
, or the number itself.
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.
1var
The JavaScript variation leverages a constant array to encapsulate decisions for values, reducing verbosity in branching and improving code simplicity.