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.
1#include <vector>
2#include <string>
3
4std::vector<std::string> fizzBuzz(int n) {
5 std::vector<std::string> result;
6 for (int i = 1; i <= n; ++i) {
7 if (i % 3 == 0 && i % 5 == 0) {
8 result.push_back("FizzBuzz");
9 } else if (i % 3 == 0) {
10 result.push_back("Fizz");
11 } else if (i % 5 == 0) {
12 result.push_back("Buzz");
13 } else {
14 result.push_back(std::to_string(i));
15 }
16 }
17 return result;
18}
19
This C++ solution utilizes the vector
class to dynamically build the result array. Strings are appended based on conditional checks for divisibility, making use of push_back
to add elements.
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.
1import
This Java implementation uses an array for the standard outputs. It calculates which output to use by computing an index, simplifying the branch logic typically involved in such solutions.