Fizz Buzz easy

Problem Statement

Given an integer n, return a string array answer (1-indexed) where:

  • answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
  • answer[i] == "Fizz" if i is divisible by 3.
  • answer[i] == "Buzz" if i is divisible by 5.
  • answer[i] == i (as a string) if none of the above conditions are true.

Example 1:

Input: n = 3 Output: ["1","2","Fizz"]

Example 2:

Input: n = 5 Output: ["1","2","Fizz","4","Buzz"]

Steps:

  1. Initialization: Create a string vector answer of size n to store the results.
  2. Iteration: Iterate through numbers from 1 to n (inclusive).
  3. Divisibility Check: For each number i:
    • Check if i is divisible by both 3 and 5 using the modulo operator (%). If true, add "FizzBuzz" to answer.
    • Otherwise, check if i is divisible by 3. If true, add "Fizz" to answer.
    • Otherwise, check if i is divisible by 5. If true, add "Buzz" to answer.
    • Otherwise, convert i to a string using to_string() and add it to answer.
  4. Return: Return the answer vector.

Explanation:

The solution uses a simple iterative approach with conditional statements to check the divisibility of each number by 3 and 5. The modulo operator (%) efficiently determines if a number is divisible by another. The to_string() function converts integers to strings for cases where the number is not divisible by 3 or 5.

Code:

#include <string>
#include <vector>

class Solution {
public:
    std::vector<std::string> fizzBuzz(int n) {
        std::vector<std::string> answer(n);
        for (int i = 1; i <= n; ++i) {
            if (i % 3 == 0 && i % 5 == 0) {
                answer[i - 1] = "FizzBuzz";
            } else if (i % 3 == 0) {
                answer[i - 1] = "Fizz";
            } else if (i % 5 == 0) {
                answer[i - 1] = "Buzz";
            } else {
                answer[i - 1] = std::to_string(i);
            }
        }
        return answer;
    }
};

Complexity:

  • Time Complexity: O(n), where n is the input integer. We iterate through the numbers from 1 to n once.
  • Space Complexity: O(n), as we store the results in a string vector of size n.