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.
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.
Complexity: O(N) time and O(N) space.
Last updated
Was this helpful?