Post

Leetcode 0412. FizzBuzz

Given an integer n, return a string array answer (1-indexed) where: - `answer[i] == "FizzBuzz"` if `i` is divisible by `3` and `5`. - `answer[i] == "Fizz"` if `i` is divisible by `3`. - `answer[i] == "Buzz"` if `i` is divisible by `5`.

Description

Given an integer n, return a string array answer (1-indexed) where:

  • answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
  • answer[i] == "Fizz" if i is divisible by 3.
  • answer[i] == "Buzz" if i is divisible by 5.
  • answer[i] == i (as a string) if none of the above conditions are true.

Example 1:

Input: n = 3
Output: [“1”,”2”,”Fizz”]

Example 2:

Input: n = 5
Output: [“1”,”2”,”Fizz”,”4”,”Buzz”]

Example 3:

Input: n = 15
Output: [“1”,”2”,”Fizz”,”4”,”Buzz”,”Fizz”,”7”,”8”,”Fizz”,”Buzz”,”11”,”Fizz”,”13”,”14”,”FizzBuzz”]

Constraints:

  • 1 <= n <= 10^4

Solution

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
import java.util.List;
import java.util.ArrayList;

class Solution {
  /**
  * Iterative Approach
  * Analysis
  * Time Complexity: BigO(n)
  * Space Complexity: BigO(n)
  */
  public List<String> fizzBuzz(int n) {
    List<String> list = new ArrayList<String>();

    for (int i = 1; i <= n; i++) {
      if (i % 3 == 0 && i % 5 == 0)
        list.add("FizzBuzz");
      else if (i % 3 == 0)
        list.add("Fizz");
      else if (i % 5 == 0)
        list.add("Buzz");
      else
        list.add(Integer.toString(i));
    }

    return list;
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
    # Iterative Approach
    # Time Complexity: BigO(n)
    # Space Complexity: BigO(n)
    def fizzBuzz(self, n: int) -> List[str]:
        arr = []
        for i in range(1, n + 1):
            if i % 3 == 0 and i % 5 == 0:
                arr.append("FizzBuzz")
            elif i % 3 == 0:
                arr.append("Fizz")
            elif i % 5 == 0:
                arr.append("Buzz")
            else:
                arr.append(str(i))
        return arr
  • if i % 3 == 0 and i % 5 == 0: can be if not i % 3 and not i % 5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
 * Iterative Approach
 * Time Complexity: BigO(n)
 * Space Complexity: BigO(n)
 */
function fizzBuzz(n: number): string[] {
  let arr = Array.from({ length: n }, (_, i) => i + 1);
  return arr.map((num) => {
    if (num % 15 == 0) return "FizzBuzz";
    else if (num % 3 == 0) return "Fizz";
    else if (num % 5 == 0) return "Buzz";
    else return `${num}`;
  });
}
This post is licensed under CC BY 4.0 by the author.