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 array answer of size n to store the results.
  2. Iteration: Iterate from 1 to n (inclusive).
  3. Divisibility Check: For each number i, check the following conditions in order:
    • If i is divisible by both 3 and 5, add "FizzBuzz" to answer.
    • Otherwise, if i is divisible by 3, add "Fizz" to answer.
    • Otherwise, if i is divisible by 5, add "Buzz" to answer.
    • Otherwise, add the string representation of i to answer.
  4. Return: Return the answer array.

Explanation

The solution directly implements the problem's requirements. The order of the if conditions is crucial. We check for divisibility by both 3 and 5 first to ensure that "FizzBuzz" is correctly assigned when a number is divisible by both. If we checked for divisibility by 3 and 5 separately before checking for both, numbers divisible by both would incorrectly be labeled only "Fizz" or "Buzz".

Code

using System;

public class Solution {
    public IList<string> FizzBuzz(int n) {
        IList<string> answer = new List<string>();
        for (int i = 1; i <= n; i++) {
            if (i % 3 == 0 && i % 5 == 0) {
                answer.Add("FizzBuzz");
            } else if (i % 3 == 0) {
                answer.Add("Fizz");
            } else if (i % 5 == 0) {
                answer.Add("Buzz");
            } else {
                answer.Add(i.ToString());
            }
        }
        return answer;
    }
}

Complexity

  • Time Complexity: O(n) - The code iterates through the numbers from 1 to n once.
  • Space Complexity: O(n) - The answer list stores n strings.