Skip to content

412. Fizz Buzz 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  vector<string> fizzBuzz(int n) {
    vector<string> ans;

    for (int i = 1; i <= n; ++i) {
      string s;
      if (i % 3 == 0)
        s += "Fizz";
      if (i % 5 == 0)
        s += "Buzz";
      ans.push_back(s.empty() ? to_string(i) : s);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public List<String> fizzBuzz(int n) {
    List<String> ans = new ArrayList<>();

    for (int i = 1; i <= n; ++i) {
      StringBuilder sb = new StringBuilder();
      if (i % 3 == 0)
        sb.append("Fizz");
      if (i % 5 == 0)
        sb.append("Buzz");
      ans.add(sb.length() == 0 ? String.valueOf(i) : sb.toString());
    }

    return ans;
  }
}
1
2
3
4
class Solution:
  def fizzBuzz(self, n: int) -> list[str]:
    d = {3: 'Fizz', 5: 'Buzz'}
    return [''.join([d[k] for k in d if i % k == 0]) or str(i) for i in range(1, n + 1)]