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:
1 <= n <= 10^4
n
will always be within the given constraints?
n
will always satisfy 1 <= n <= 10^4
.n
.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"]
}
}
O(n)
, where n
is the input number. We iterate from 1 to n
exactly once.O(n)
, as we are storing the result in a list which has n
elements.This solution efficiently handles the problem within the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?