Fizz Buzz - Problem
The classic FizzBuzz problem is a popular programming exercise often used in coding interviews and programming assessments. Your task is to generate a sequence of strings based on specific divisibility rules.
Given an integer n, return a string array answer (1-indexed) where:
answer[i] == "FizzBuzz"ifiis divisible by both 3 and 5answer[i] == "Fizz"ifiis divisible by 3 but not 5answer[i] == "Buzz"ifiis divisible by 5 but not 3answer[i] == i(as a string) if none of the above conditions are true
Example: For n = 15, the sequence would be: ["1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz"]
Input & Output
example_1.py โ Small Input
$
Input:
n = 3
โบ
Output:
["1", "2", "Fizz"]
๐ก Note:
1 and 2 are not divisible by 3 or 5, so we output their string representations. 3 is divisible by 3, so we output "Fizz".
example_2.py โ Medium Input
$
Input:
n = 5
โบ
Output:
["1", "2", "Fizz", "4", "Buzz"]
๐ก Note:
Numbers 1, 2, and 4 become their string representations. 3 is divisible by 3 ("Fizz"), and 5 is divisible by 5 ("Buzz").
example_3.py โ FizzBuzz Case
$
Input:
n = 15
โบ
Output:
["1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz"]
๐ก Note:
This example shows all cases: regular numbers, Fizz (multiples of 3), Buzz (multiples of 5), and FizzBuzz (multiples of both 3 and 5). The number 15 is divisible by both 3 and 5, so it becomes "FizzBuzz".
Visualization
Tap to expand
Understanding the Visualization
1
Count Normally
Start counting from 1, saying each number
2
Apply Fizz Rule
When you reach a multiple of 3, say 'Fizz' instead
3
Apply Buzz Rule
When you reach a multiple of 5, say 'Buzz' instead
4
Apply FizzBuzz Rule
When you reach a multiple of both 3 and 5, say 'FizzBuzz'
Key Takeaway
๐ฏ Key Insight: FizzBuzz is fundamentally about applying conditional logic in the correct order - always check the most specific condition (divisible by both) first, then the individual conditions.
Time & Space Complexity
Time Complexity
O(n)
We iterate through each number from 1 to n exactly once, performing constant time operations
โ Linear Growth
Space Complexity
O(n)
We need to store n strings in the result array
โก Linearithmic Space
Constraints
- 1 โค n โค 104
- The output should be a string array of length n
- Follow-up: Could you solve this without using the modulo operator?
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code