FizzBuzz – Solution & Complexity
1. Understand the Replacement Rules
- For every number from
1throughn, return one string. - Multiples of
3becomeFizz, multiples of5becomeBuzz. - Multiples of both must become
FizzBuzz, not just one of the two words.
2. Check the Most Specific Case First
- A number divisible by both
3and5is divisible by15. - Check this case before checking only
3or only5. - Otherwise
15would incorrectly be labeled as justFizzor justBuzz.
3. Loop Through the Range
- Use
range(1, n + 1)because the sequence includes both endpoints:1andn. - Append the correct string for each number.
- Convert normal numbers with
str(num).
4. Handle Input Robustly
- The problem describes
nas an integer, but JSON input can sometimes provide numeric-looking values as strings. - Converting with
int(n)makes the function tolerant of either form. - The output remains a list of strings.
5. Complete Solution and Complexity
- The final solution makes one pass from
1tonand applies the divisibility rules. - Time complexity is O(n).
- Space complexity is O(n) for the returned list.