Sweaty Imposter

Fizz Buzz

EasyArrays & HashingNeetCode 150JuniorOpen on LeetCodeUpdated

You're given an integer n. Return a list of n strings describing the numbers 1 through n in order, so answer[0] is for 1. A number divisible by both 3 and 5 becomes "FizzBuzz", one divisible by 3 only becomes "Fizz", one divisible by 5 only becomes "Buzz", and any other number is written as itself, like "7".

Examples

n = 3 returns ["1","2","Fizz"]

1 and 2 aren't divisible by 3 or 5, so they're written as numbers. 3 is divisible by 3, so it becomes "Fizz".

n = 5 returns ["1","2","Fizz","4","Buzz"]

4 is written as "4", and 5 is divisible by 5 but not 3, so it becomes "Buzz".

n = 15 returns ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]

15 is the first number divisible by both 3 and 5, so it becomes "FizzBuzz". Along the way, 6, 9 and 12 become "Fizz" and 10 becomes "Buzz".

Constraints

  • 1 <= n <= 10^4

Hints

Hint 1

Each number's label depends only on whether 3 and 5 divide it. Which case has to be checked before the others?

Hint 2
A pointer toward the approach
Hint 3
The full approach, step by step

Drill This: Your Approach First

Approach

Loop i from 1 to n and pick each entry with the modulo operator. Test i % 15 == 0 first, since a number divisible by both 3 and 5 is divisible by 15, then i % 3, then i % 5, and fall back to str(i). The order matters because the chain stops at the first match. Beyond the output list itself, only the loop counter is used.

Time

O(n)

Space

O(1)

Pitfall

Checking i % 3 before the both-divisible case makes 15 match "Fizz" and stop, so "FizzBuzz" never appears. Also count from 1 through n: looping over range(n) starts at 0 and misses n.

Solutions

class Solution {
    public List<String> fizzBuzz(int n) {
        List<String> out = new ArrayList<>(n);
        for (int i = 1; i <= n; i++) {
            if (i % 15 == 0) out.add("FizzBuzz");
            else if (i % 3 == 0) out.add("Fizz");
            else if (i % 5 == 0) out.add("Buzz");
            else out.add(Integer.toString(i));
        }
        return out;
    }
}
Drill This