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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
n = 15,

Return:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"
]

Analysis

Brute-Force

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public List<String> fizzBuzz(int n) {
if (n <= 0) {
return new ArrayList<>();
}

List<String> result = new ArrayList<>();
for (int i = 1; i <= n; ++i) {
if (i % 3 == 0 && i % 5 == 0) {
result.add("FizzBuzz");
} else if (i % 3 == 0) {
result.add("Fizz");
} else if (i % 5 == 0) {
result.add("Buzz");
} else {
result.add(String.valueOf(i));
}
}

return result;
}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public List<String> fizzBuzz(int n) {
if (n <= 0) {
return new ArrayList<>();
}

List<String> result = new ArrayList<String>();

for (int i = 1; i <= n; ++i) {
boolean divisibleBy3 = (i % 3 == 0);
boolean divisibleBy5 = (i % 5 == 0);
String str = "";

if (divisibleBy3) {
str += "Fizz";
}

if (divisibleBy5) {
str += "Buzz";
}

// if (divisibleBy7) {
// str += "Jazz";
// }

if (str.equals("")) { // Not divisible by 3 or 5, add the number
str += Integer.toString(i);
}

result.add(str);
}

return result;
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public List<String> fizzBuzz(int n) {
if (n <= 0) {
return new ArrayList<>();
}

List<String> result = new ArrayList<>();

Map<Integer, String> map = new HashMap<>() {{
put(3, "Fizz");
put(5, "Buzz");
}};

for (int i = 1; i <= n; ++i) {
String str = "";

for (int key : map.keySet()) {
if (num % key == 0) {
str += map.get(key);
}
}

if (str.equals("")) {
str += Integer.toString(num);
}

result.add(str);
}

return result;
}

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