Attempting a FizzBuzz recursive solution in Java to return a list of Strings with n iterations. For example, n = 4 should output ["1","2","Fizz", 4]. However, with my current code the output is just ["4"]. Why is my solution not executing the recursive function? Any other critiques are appreciated!
class Solution {
public List<String> fizzBuzz(int n) {
//create variable to return list of strings
List<String> fbList = new ArrayList<String>();
//base case 1
if(n == 0){
fbList.add(Integer.toString(0));
}
//base case 2
else if(n == 1){
fbList.add(Integer.toString(1));
}
//OW take n and begin reducing recursively from, n - 1
else{
if(n % 3 == 0){
fbList.add("Fizz");
}
else if(n % 5 == 0){
fbList.add("Buzz");
}
else if((n % 3 == 0) && (n % 5 == 0)){
fbList.add("FizzBuzz");
}
else{
fbList.add(Integer.toString(n));
}
//recursive function call
fizzBuzz(n - 1);
}
return fbList;
}
}
The problem is that with every recursive call, a new List
is created. You return the list but:
fizzBuzz(n - 1);
You are ignoring the return value of the recursive calls. To fix this you can do:
fbList.addAll(0, fizzBuzz(n - 1));
Which will utilize the method addAll
to add all the elements returned by the recursive calls. This returns:
[1, 2, Fizz, 4]
However this is rather expensive for an ArrayList
. You could change this to a LinkedList
, which would allow for linear time adding.
Also you if/else if/else
chain is out of order. if((n % 3 == 0) && (n % 5 == 0))
should be before if(n % 3 == 0)
and if(n % 5 == 0)
. Otherwise it will always enter the if(n % 5 == 0)
or if(n % 3 == 0)
:
if((n % 3 == 0) && (n % 5 == 0)){
fbList.add("FizzBuzz");
}
else if(n % 3 == 0){
fbList.add("Fizz");
}
else if(n % 5 == 0){
fbList.add("Buzz");
}