Leetcode 412. Fizz Buzz

Problem Explanation

The problem requires us to output a list of strings, each string representing a number from 1 to n, with the following conditions:

  • For numbers which are multiples of three, it should output “Fizz” instead of the number.
  • For multiples of five, it should output “Buzz”.
  • For numbers which are multiples of both three and five it should output “FizzBuzz”.

Walkthrough with an example

Let's take n = 6 as an example. For this scenario the output should be ['1', '2', 'Fizz', '4', 'Buzz', 'Fizz']. Here's the step-by-step process:

  • Start with an empty string, iterate from 1 to n (included).
  • At each iteration, if the number is divisible by 3, append 'Fizz' to the string.
  • If the number is divisible by 5, append 'Buzz' to the string.
  • If the number is not divisible by either 3 or 5, convert the number to string and append it.
  • After checking these conditions, add resultant string to the output list.

The approach used here is straightforward iteration of numbers and checking for divisibility by 3 and 5.

Python Solution

1
2python
3class Solution:
4    def fizzBuzz(self, n: int) -> List[str]:
5        res = []
6        for i in range(1,n+1):
7            string = ""
8            if i%3==0:
9                string += "Fizz"
10            if i%5==0:
11                string += "Buzz"
12            if not string:
13                string = str(i)
14            res.append(string)
15        return res

Java Solution

1
2java
3class Solution {
4    public List<String> fizzBuzz(int n) {
5        List<String> res = new ArrayList<>();
6        for(int i=1;i<=n;i++){
7            StringBuilder str = new StringBuilder();
8            if(i%3==0){
9                str.append("Fizz");
10            } 
11            if(i%5==0){
12                str.append("Buzz");
13            } 
14            if(str.length()==0){
15                str.append(Integer.toString(i));
16            } 
17            res.add(str.toString());
18        }
19        return res;
20    }
21}

JavaScript Solution

1
2javascript
3var fizzBuzz = function(n) {
4    let res = [];
5    for(let i=1;i<=n;i++){
6        let str = "";
7        if(i%3==0){
8           str+="Fizz";
9        } 
10        if(i%5==0){
11           str+="Buzz";
12        } 
13        if(str === "" ){
14           str+=i;
15       } 
16        res.push(str);
17    }
18    return res;
19};

C++ Solution

1
2cpp
3class Solution {
4public:
5    vector<string> fizzBuzz(int n) {
6        vector<string> res;
7        for(int i=1;i<=n;i++){
8            string str = "";
9            if(i%3==0){
10                str+="Fizz";
11            } 
12            if(i%5==0){
13                str+="Buzz";
14            } 
15            if(str == "" ){
16                str=to_string(i);
17            } 
18            res.push_back(str);
19        }
20        return res;
21    }
22};

C# Solution

1
2csharp
3public class Solution {
4    public IList<string> FizzBuzz(int n) {
5        List<string> res = new List<string>();
6        for(int i=1;i<=n;i++){
7            StringBuilder str = new StringBuilder();
8            if(i%3==0){
9                str.Append("Fizz");
10            } 
11            if(i%5==0){
12                str.Append("Buzz");
13            }
14            if(str.Length==0){
15                str.Append(i);
16            } 
17            res.Add(str.ToString());
18        }
19        return res;
20    }
21}

In each solution above, we iterate the number from 1 to n. If number is divisible by 3, we append 'Fizz' to string. If number is divisible by 5, we append 'Buzz' to string. Else, we append the number itself to string. We then append this string to the result list.## Ruby Solution

1
2ruby
3def fizz_buzz(n)
4    res = []
5    (1..n).each do |i|
6        str = ""
7        if i % 3 == 0
8            str += "Fizz"
9        end
10        if i % 5 == 0
11            str += "Buzz"
12        end
13        if str.empty?
14            str = i.to_s
15        end
16        res << str
17    end
18    return res
19end

Swift Solution

1
2swift
3class Solution {
4    func fizzBuzz(_ n: Int) -> [String] {
5        var res: [String] = []
6        for i in 1...n {
7            var str = ""
8            if i % 3 == 0 {
9                str += "Fizz"
10            }
11            if i % 5 == 0 {
12                str += "Buzz"
13            }
14            if str.isEmpty {
15                str = String(i)
16            }
17            res.append(str)
18        }
19        return res
20    }
21}

The Ruby solution uses a similar approach using a for loop from 1 to n. If i is divisible by 3, it appends "fizz" to the string. If i is divisible by 5, it appends "Buzz". If the string is empty, it means that the number is not divisible by 3 or 5, and we append the number itself as a string.

The Swift solution mimics the earlier solutions using Swift's language specifications.

In each of these solutions, we are leveraging the same core logic to solve the problem: Iterating through the numbers from 1 to 'n', checking each whether it's divisible by 3 or 5 or both, and accordingly adding the appropriate value to our resulting array or list.

Regardless of the language used, the essential principles of the solution remain the same. The variation across different languages mainly lies in differences in syntax, data structures available, and method/operation naming conventions.


Got a question? Ask the Teaching Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.


TA 👨‍🏫