The Algorithm
Explore the FizzBuzz solution with detailed code explanation
Algorithm Approach
Iterate from 1 to N. For each integer, check divisibility by the Fizz divisor, the Buzz divisor, and both. Assign the appropriate label — Fizz, Buzz, FizzBuzz, or the number itself — and collect the results.
Complexity Analysis
Time Complexity:
O(n) Single pass through 1..N
O(n) Single pass through 1..N
Space Complexity:
O(n) Result array of N items
O(n) Result array of N items
Step-by-Step Process
- Loop i from 1 to N (inclusive)
- Check
i % fizz === 0andi % buzz === 0 - If both are true → push "FizzBuzz"
- Else if only Fizz → push "Fizz"
- Else if only Buzz → push "Buzz"
- Otherwise → push the number as a string
Implementation
Example Walkthrough (Fizz = 3, Buzz = 5, N = 15)
| i | i % 3 | i % 5 | Output |
|---|---|---|---|
| 1 | 1 | 1 | 1 |
| 2 | 2 | 2 | 2 |
| 3 | 0 | 3 | Fizz |
| 4 | 1 | 4 | 4 |
| 5 | 2 | 0 | Buzz |
| 6 | 0 | 1 | Fizz |
| 7 | 1 | 2 | 7 |
| 8 | 2 | 3 | 8 |
| 9 | 0 | 4 | Fizz |
| 10 | 1 | 0 | Buzz |
| 11 | 2 | 1 | 11 |
| 12 | 0 | 2 | Fizz |
| 13 | 1 | 3 | 13 |
| 14 | 2 | 4 | 14 |
| 15 | 0 | 0 | FizzBuzz |