algoadvance

Leetcode 412. Fizz Buzz

Problem Statement

The problem “Fizz Buzz” is a classic problem often used in coding interviews. The task is to write a program that outputs numbers from 1 to n. However, for multiples of three, it should output “Fizz” instead of the number and for multiples of five, it should output “Buzz”. For numbers that are multiples of both three and five, it should output “FizzBuzz”.

Constraints:

Clarifying Questions

  1. Should the return type be a list of strings where each element is the appropriate output for each number in the sequence?
    • Yes, return a list where each element is a string representation of the number or the appropriate “Fizz”, “Buzz”, “FizzBuzz”.
  2. Can we assume the input n will always be within the given constraints?
    • Yes, the input n will always satisfy 1 <= n <= 10^4.

Strategy

  1. Initialize a List: Create a list to store the results.
  2. Loop through Numbers: Iterate through each number from 1 to n.
  3. Check Conditions:
    • For multiples of both 3 and 5, append “FizzBuzz”.
    • For multiples of 3, append “Fizz”.
    • For multiples of 5, append “Buzz”.
    • For other numbers, append the string representation of the number.
  4. Return the List: After the loop completes, return the list.

Code

import java.util.ArrayList;
import java.util.List;

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

    // Main function to test the solution
    public static void main(String[] args) {
        FizzBuzz fb = new FizzBuzz();
        System.out.println(fb.fizzBuzz(15)); // Expected output: [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz"]
    }
}

Time Complexity

This solution efficiently handles the problem within the given constraints.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI