Reference: LeetCode
Difficulty: Easy
Problem
Write a program that outputs the string representation of numbers from
1
ton
.
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"
.
Example:
1 | n = 15, |
Analysis
Brute-Force
1 | public List<String> fizzBuzz(int n) { |
Time: $O(N)$
Space: $O(1)$
String Concatenation
If a new requirement is that if the number is divisible by 7
, we would add more if
s. A better way of doing this is to use string concatenation.
- Divisible by 3
- Divisible by 5
- Divisible by 7
- Divisible by 3 and 5
- Divisible by 3 and 7
- Divisible by 7 and 3
- Divisible by 3 and 5 and 7
- Not divisible by 3 or 5 or 7.
Note: String to Integer -> Use String.valueOf()
or Integer.toString()
1 | public List<String> fizzBuzz(int n) { |
Time: $O(N)$
Space: $O(1)$
Hash It!
Reference: LeetCode Solution
This approach is an optimization over approach 2. When the number of mappings are limited, approach 2 looks good. But what if you face a tricky interviewer and he decides to add too many mappings?
Having a condition for every mapping is not feasible or may be we can say the code might get ugly and tough to maintain.
Note: Learn that a collection object can be initialized in this way.
1 | public List<String> fizzBuzz(int n) { |
Time: $O(N)$
Space: $O(1)$