412. Fizz Buzz

Reference: LeetCode
Difficulty: Easy

Problem

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".

Example:

Analysis

Brute-Force

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 ifs. 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()

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.

Time: $O(N)$
Space: $O(1)$

Comment
Junhao Wang
a software engineering cat