LeetCode 412: Fizz Buzz Solution

Master LeetCode problem 412 (Fizz Buzz), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

412. Fizz Buzz

Problem Explanation

Explanation

  • We iterate from 1 to n and for each number, we check if it is divisible by 3, 5, or both.
  • If it is divisible by both 3 and 5, we add "FizzBuzz" to the answer array.
  • If it is divisible by 3 only, we add "Fizz" to the answer array.
  • If it is divisible by 5 only, we add "Buzz" to the answer array.
  • If none of the above conditions are met, we add the number itself as a string to the answer array.

Time Complexity: O(n) where n is the input integer.

Space Complexity: O(1) excluding the space required for the output array.

Solution Code

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;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 412 (Fizz Buzz)?

This page provides optimized solutions for LeetCode problem 412 (Fizz Buzz) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 412 (Fizz Buzz)?

The time complexity for LeetCode 412 (Fizz Buzz) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 412 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 412 in Java, C++, or Python.

Back to LeetCode Solutions