Fizz Buzz

Easy MathString

Problem

Given an integer n, return a list of strings where the i-th (1-indexed) entry is "FizzBuzz" if i is divisible by 15, "Fizz" if by 3, "Buzz" if by 5, otherwise the number itself.

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

Approach — Core Patterns

This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: see the walkthrough below.

Solution code

Python

class Solution:
    def fizzBuzz(self, n):
        res = []
        for i in range(1, n + 1):
            if i % 15 == 0:
                res.append("FizzBuzz")
            elif i % 3 == 0:
                res.append("Fizz")
            elif i % 5 == 0:
                res.append("Buzz")
            else:
                res.append(str(i))
        return res

Java

import java.util.ArrayList;
class Solution {
    public List<String> fizzBuzz(int n) {
        List<String> result = new ArrayList<>(n);
        for (int i = 1; i <= n; i++) {
            boolean divBy3 = i % 3 == 0;
            boolean divBy5 = i % 5 == 0;
            if (divBy3 && divBy5) {
                result.add("FizzBuzz");
            } else if (divBy3) {
                result.add("Fizz");
            } else if (divBy5) {
                result.add("Buzz");
            } else {
                result.add(Integer.toString(i));
            }
        }
        return result;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Fizz Buzz interactively → ← All solutions