412. Fizz Buzz
Model: qwen2.5-coder:14b
Topics:
FAANG asked: 1
Acceptance rate: 63.6%
Problem Breakdown
The problem requires writing a program that outputs the string representation of numbers from 1 to n. For multiples of three, it should output “Fizz” instead of the number, and for multiples of five, it should output “Buzz”. If a number is a multiple of both three and five, it should output “FizzBuzz”.
Inputs:
- An integer
nrepresenting the upper limit.
Outputs:
- A list of strings where each element is either the string representation of a number or “Fizz”, “Buzz”, or “FizzBuzz” based on the rules provided.
Implicit Constraints/Edge Cases:
- If
nis less than 1, the output should be an empty list. - The input
nis expected to be a positive integer.
Intuition
A brute-force approach would involve iterating through numbers from 1 to n and checking each number individually for divisibility by 3 and 5. This approach is straightforward but inefficient as it involves multiple conditional checks for each number.
The key insight is to use the modulo operator to determine if a number is divisible by 3 or 5, and then construct the output string based on these conditions. This reduces the complexity compared to checking each condition separately.
Approach
- Initialize an empty list
resultto store the output strings. - Iterate through numbers from 1 to n:
- For each number, check if it is divisible by both 3 and 5 using the modulo operator (
%). If true, append “FizzBuzz” to the result list. - If not, check if the number is divisible by 3. If true, append “Fizz” to the result list.
- If not, check if the number is divisible by 5. If true, append “Buzz” to the result list.
- If none of the above conditions are met, convert the number to a string and append it to the result list.
- For each number, check if it is divisible by both 3 and 5 using the modulo operator (
- Return the
resultlist.
Complexity Analysis
- Time Complexity: O(n), where n is the input number. This is because we iterate through each number from 1 to n once.
- Space Complexity: O(n), as we store the output strings in a list of size n.
Solution
def fizzBuzz(n):
result = []
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
result.append("FizzBuzz")
elif i % 3 == 0:
result.append("Fizz")
elif i % 5 == 0:
result.append("Buzz")
else:
result.append(str(i))
return result
Edge Cases Handled
- n = 0 or n < 1: The loop does not execute, and an empty list is returned.
- n = 1: Only “1” is appended to the result list.
- n = 3: The output is [“1”, “2”, “Fizz”].
- n = 5: The output is [“1”, “2”, “Fizz”, “4”, “Buzz”].
- n = 15: The output is [“1”, “2”, “Fizz”, “4”, “Buzz”, “Fizz”, “7”, “8”, “Fizz”, “Buzz”, “11”, “Fizz”, “13”, “14”, “FizzBuzz”].