Fizz Buzz easy

Problem Statement

Given an integer n, return a string array answer (0-indexed) where answer[i] is equal to:

  • "FizzBuzz" if i is divisible by 3 and 5.
  • "Fizz" if i is divisible by 3.
  • "Buzz" if i is divisible by 5.
  • 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 to Solve

  1. Initialization: Create a string array answer of size n to store the results.
  2. Iteration: Iterate through numbers from 1 to n (inclusive).
  3. Divisibility Checks: 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, add the string representation of i to answer.
  4. Return: Return the answer array.

Explanation

The solution uses a simple iterative approach with conditional statements to check the divisibility of each number. The modulo operator (%) efficiently determines if a number is divisible by another. The code is straightforward and easy to understand. The order of the checks is important to ensure that "FizzBuzz" is prioritized over "Fizz" and "Buzz".

Code (Java)

class Solution {
    public List<String> fizzBuzz(int n) {
        List<String> answer = new ArrayList<>();
        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(String.valueOf(i));
            }
        }
        return answer;
    }
}

Complexity Analysis

  • Time Complexity: O(n) - The code iterates through the numbers from 1 to n once.
  • Space Complexity: O(n) - The answer array stores n strings. The space used is proportional to the input size.