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.
1import java.util.ArrayList;
2import java.util.List;
3
4public class Solution {
5 public List<String> fizzBuzz(int n) {
6 List<String> result = new ArrayList<>();
7 for (int i = 1; i <= n; i++) {
8 if (i % 3 == 0 && i % 5 == 0) {
9 result.add("FizzBuzz");
10 } else if (i % 3 == 0) {
11 result.add("Fizz");
12 } else if (i % 5 == 0) {
13 result.add("Buzz");
14 } else {
15 result.add(Integer.toString(i));
16 }
17 }
18 return result;
19 }
20}
21
This Java solution uses an ArrayList
to store the result. The List is built by iterating over each number and applying the appropriate checks to append either 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.
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.