KatInterview

412. Fizz Buzz

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to generate a list of strings for numbers from 1 to n. The string for a given number i is determined by its divisibility by 3 and 5:

Solution

Fizz Buzz in Python

class Solution:
    def fizzBuzz(self, n: int) -> List[str]:
        # Initialize an empty list to store the results.
        answer = []
        
        # Loop through numbers from 1 to n (inclusive).
        for i in range(1, n + 1):
            # The order of conditions is important.
            # Check for divisibility by both 3 and 5 (i.e., 15) first.
            if i % 15 == 0:
                answer.append("FizzBuzz")
            # Then, check for divisibility by 3.
            elif i % 3 == 0:
                answer.append("Fizz")
            # Then, check for divisibility by 5.
            elif i % 5 == 0:
                answer.append("Buzz")
            # If none of the above, append the number as a string.
            else:
                answer.append(str(i))
                
        return answer

Fizz Buzz in Java

class Solution {
    public List<String> fizzBuzz(int n) {
        // Initialize a list of strings. Providing initial capacity is a good practice.
        List<String> answer = new ArrayList<>(n);
        
        // Loop from 1 to n (inclusive).
        for (int i = 1; i <= n; i++) {
            // Check for divisibility by 15 (i.e., by both 3 and 5).
            // This condition must be checked first.
            if (i % 15 == 0) {
                answer.add("FizzBuzz");
            } 
            // Else, check for divisibility by 3.
            else if (i % 3 == 0) {
                answer.add("Fizz");
            } 
            // Else, check for divisibility by 5.
            else if (i % 5 == 0) {
                answer.add("Buzz");
            } 
            // If none of the above conditions are met, add the number as a string.
            else {
                answer.add(String.valueOf(i));
            }
        }
        
        return answer;
    }
}

Fizz Buzz in C++

class Solution {
public:
    vector<string> fizzBuzz(int n) {
        // Initialize a vector of strings to store the results.
        vector<string> answer;
        // Pre-allocating memory can be a minor optimization for large n.
        answer.reserve(n);
        
        // Loop from 1 to n (inclusive).
        for (int i = 1; i <= n; ++i) {
            // Check for divisibility by 15 (both 3 and 5) first.
            // This is crucial because if we check for 3 or 5 first,
            // numbers divisible by 15 would be handled by those cases.
            if (i % 15 == 0) {
                answer.push_back("FizzBuzz");
            } 
            // Else, check for divisibility by 3.
            else if (i % 3 == 0) {
                answer.push_back("Fizz");
            } 
            // Else, check for divisibility by 5.
            else if (i % 5 == 0) {
                answer.push_back("Buzz");
            } 
            // If none of the above, convert the number to a string.
            else {
                answer.push_back(to_string(i));
            }
        }
        
        // Return the final list.
        return answer;
    }
};

Fizz Buzz in TypeScript

function fizzBuzz(n: number): string[] {
    // Initialize an array to store the string results.
    const answer: string[] = [];
    
    // Loop from 1 up to and including n.
    for (let i = 1; i <= n; i++) {
        // We must check for divisibility by 15 first, as numbers
        // divisible by 15 are also divisible by 3 and 5.
        // Checking this first ensures the correct "FizzBuzz" output.
        if (i % 15 === 0) {
            answer.push("FizzBuzz");
        } 
        // If not divisible by 15, check for divisibility by 3.
        else if (i % 3 === 0) {
            answer.push("Fizz");
        } 
        // If not divisible by 3, check for divisibility by 5.
        else if (i % 5 === 0) {
            answer.push("Buzz");
        } 
        // If none of the above, the number is not divisible by 3 or 5.
        // Convert the number to a string and add it to the array.
        else {
            answer.push(String(i));
        }
    }
    
    // Return the completed array.
    return answer;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.