412. Fizz Buzz LeetCode Solution

In this guide, you will get 412. Fizz Buzz LeetCode Solution with the best time and space complexity. The solution to Fizz Buzz problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Fizz Buzz solution in C++
  4. Fizz Buzz solution in Java
  5. Fizz Buzz solution in Python
  6. Additional Resources
412. Fizz Buzz LeetCode Solution image

Problem Statement of Fizz Buzz

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”]
Example 3:
Input: n = 15
Output: [“1″,”2″,”Fizz”,”4″,”Buzz”,”Fizz”,”7″,”8″,”Fizz”,”Buzz”,”11″,”Fizz”,”13″,”14″,”FizzBuzz”]

Constraints:

1 <= n <= 104

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

412. Fizz Buzz LeetCode Solution in C++

class Solution {
 public:
  vector<string> fizzBuzz(int n) {
    vector<string> ans;

    for (int i = 1; i <= n; ++i) {
      string s;
      if (i % 3 == 0)
        s += "Fizz";
      if (i % 5 == 0)
        s += "Buzz";
      ans.push_back(s.empty() ? to_string(i) : s);
    }

    return ans;
  }
};
/* code provided by PROGIEZ */

412. Fizz Buzz LeetCode Solution in Java

class Solution {
  public List<String> fizzBuzz(int n) {
    List<String> ans = new ArrayList<>();

    for (int i = 1; i <= n; ++i) {
      StringBuilder sb = new StringBuilder();
      if (i % 3 == 0)
        sb.append("Fizz");
      if (i % 5 == 0)
        sb.append("Buzz");
      ans.add(sb.length() == 0 ? String.valueOf(i) : sb.toString());
    }

    return ans;
  }
}
// code provided by PROGIEZ

412. Fizz Buzz LeetCode Solution in Python

class Solution:
  def fizzBuzz(self, n: int) -> list[str]:
    d = {3: 'Fizz', 5: 'Buzz'}
    return [''.join([d[k] for k in d if i % k == 0]) or str(i) for i in range(1, n + 1)]
# code by PROGIEZ

Additional Resources

See also  208. Implement Trie (Prefix Tree) LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.