Fizz Buzz - Problem

Given an integer n, return a string array answer (1-indexed) where:

  • answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
  • answer[i] == "Fizz" if i is divisible by 3.
  • answer[i] == "Buzz" if i is divisible by 5.
  • answer[i] == i (as a string) if none of the above conditions are true.

Input & Output

Example 1 — Basic Case
$ Input: n = 3
Output: ["1","2","Fizz"]
💡 Note: Numbers 1-3: 1 and 2 are not divisible by 3 or 5, so output as strings. 3 is divisible by 3, so output "Fizz".
Example 2 — Include Buzz
$ Input: n = 5
Output: ["1","2","Fizz","4","Buzz"]
💡 Note: Numbers 1-5: 1,2,4 output as strings. 3 divisible by 3 → "Fizz". 5 divisible by 5 → "Buzz".
Example 3 — Include FizzBuzz
$ Input: n = 15
Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
💡 Note: Numbers 1-15: 15 is divisible by both 3 and 5, so output "FizzBuzz". Other multiples follow individual rules.

Constraints

  • 1 ≤ n ≤ 104

Visualization

Tap to expand
Fizz Buzz Problem INPUT Integer n n = 3 Process numbers 1 to n: 1 2 3 Rules: i%15==0 --> "FizzBuzz" i%3==0 --> "Fizz" i%5==0 --> "Buzz" else --> string(i) ALGORITHM STEPS 1 Check i=1 1%3!=0, 1%5!=0 Result: "1" 2 Check i=2 2%3!=0, 2%5!=0 Result: "2" 3 Check i=3 3%3==0 (divisible!) Result: "Fizz" 4 Build Result Collect all strings into answer array Optimized: Single Modulo Check %15 first, then %3, then %5 FINAL RESULT Output Array: [0] "1" [1] "2" [2] "Fizz" ["1","2","Fizz"] OK 3 elements returned for n = 3 i=1: num | i=2: num | i=3: Fizz Key Insight: The optimized approach checks divisibility by 15 first (for FizzBuzz), avoiding separate checks for 3 AND 5. This reduces the number of modulo operations from 4 to at most 3 per iteration, improving efficiency. TutorialsPoint - Fizz Buzz | Optimized - Single Modulo Check
Asked in
Apple 25 Amazon 20 Microsoft 15 Google 10
125.0K Views
High Frequency
~10 min Avg. Time
3.2K 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