Java O(n) Easy To Understand Solution That Interviewers Are Looking For


  • 0
    B

    Explanation
    If you are asked this question, you are expected to understand basic if...else if...else and for loop syntax, and why you should be using them, along with a basic understanding of math.

    The whole point of this question is to see if you can code at all, and if you can structure your code nicely.

    Time Complexity
    The time complexity of this question is O(n) where n is the given input n.

    class Solution {
        public List<String> fizzBuzz(int n) {
            List<String> result = new ArrayList<>();
            
            for (int i = 1; i <= n; i++) {
                // Divisible by both 3 and 5
                if (i % 3 == 0 && i % 5 == 0) {
                    result.add("FizzBuzz");
                } 
                // Divisible by 3
                else if (i % 3 == 0) {
                    result.add("Fizz");
                } 
                // Divisible by 5
                else if (i % 5 == 0) {
                    result.add("Buzz");
                } 
                else {
                    result.add(Integer.toString(i));
                }
            }
            return result;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.