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" if i is divisible by both 3 and 5
  • answer[i] == "Fizz" if i is divisible by 3 but not 5
  • answer[i] == "Buzz" if i is divisible by 5 but not 3
  • answer[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
FizzBuzz Pattern (First 15 Numbers)Pattern repeats every 15 numbers:12Fizz4BuzzFizz78FizzBuzz11Fizz1314FizzBuzzLegend:Regular numbersFizz (รท3)Buzz (รท5)FizzBuzz (รท3 and รท5)
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

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

We need to store n strings in the result array

n
2n
โšก 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?
Asked in
Google 25 Amazon 20 Microsoft 18 Meta 15
89.6K Views
Very High Frequency
~8 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen