Fizz Buzz (412)
Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
Approach1:
In this approach, we simply write the code as the problem states, solution should be clear and readable. The only caveat is that we need to check the condition that checks for the multiple of 3 and 5 first (can also be written as multiple of 15) before setting the other conditions for the multiple of 3 individually and then 5 because any number divisible by 15 is also divisbile by 3 or 5.
class Solution {
public List<String> fizzBuzz(int n) {
List<String> list = new ArrayList<>();
for(int i = 1; i <= n; i++){
if(i % 3 == 0 && i % 5 == 0){
list.add("FizzBuzz");
}
else if(i % 5 == 0){
list.add("Buzz");
}
else if(i % 3 == 0){
list.add("Fizz");
}
else{
list.add(i + "");
}
}
return list;
}
}
Complexity: O(N) time and O(N) space.
Approach2:
In a scenario where you would want to optimize the code to make it more concise and extendable, there's another approach that could be implemented and for that you'll use a Map.
Insert the encoding options inside a Map, with the Key being the number and the Value being the corresponding Word
I want to use a LinkedHashMap due to the insertion Order Property compared to a regular Hashmap which just stores the lements in a random order. (A TreeMap could also be used but only if you define the order of how you want to concat the words with a Lambda Comparator in it's constructor)
As we iterate thorugh each number from 1 to n, we check if that number has an encoding option by iterating trough the keys of the map.
class Solution {
public List<String> fizzBuzz(int n) {
if (n <= 0) {
return new ArrayList();
}
Map<Integer, String> map = new LinkedHashMap<>();
map.put(15, "FizzBuzz");
map.put(3, "Fizz");
map.put(5, "Buzz");
// map.put(7, "Yuzz");
// map.put(9, "Mozz"); add more encoding options here ...
List<String> numsStrs = new LinkedList();
for (int i = 1; i <= n; i++) {
StringBuilder encoded = new StringBuilder();
for (int num : map.keySet()) {
if (i % num == 0){
encoded.append(map.get(num));
break;
}
}
numsStrs.add((encoded.length() == 0) ? String.valueOf(i) : encoded.toString());
}
return numsStrs;
}
}
Complexity: O(N) time and O(N) space.
Last updated
Was this helpful?