Tutorialspoint
Problem
Solution
Submissions

FizzBuzz

Certification: Basic Level Accuracy: 60% Submissions: 5 Points: 5

Write a JavaScript program that prints numbers from 1 to n. For multiples of 3, print "Fizz" instead of the number. For multiples of 5, print "Buzz" instead of the number. For numbers that are multiples of both 3 and 5, print "FizzBuzz". Return an array containing all the results.

Example 1
  • Input: n = 15
  • Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
  • Explanation:
    • Numbers 1 and 2 remain as strings "1" and "2".
    • Number 3 is divisible by 3, so it becomes "Fizz".
    • Number 5 is divisible by 5, so it becomes "Buzz".
    • Number 15 is divisible by both 3 and 5, so it becomes "FizzBuzz".
Example 2
  • Input: n = 5
  • Output: ["1","2","Fizz","4","Buzz"]
  • Explanation:
    • Numbers 1, 2, and 4 remain as strings.
    • Number 3 is divisible by 3, so it becomes "Fizz".
    • Number 5 is divisible by 5, so it becomes "Buzz".
Constraints
  • 1 ≤ n ≤ 10^4
  • You must return an array of strings
  • Time Complexity: O(n)
  • Space Complexity: O(n)
ArraysStringsEYSwiggy
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Create an empty array to store the results
  • Use a loop to iterate from 1 to n
  • For each number, check divisibility by 3 and 5 using modulo operator
  • Check for divisibility by both 3 and 5 first (FizzBuzz case)
  • Then check for divisibility by 3 only (Fizz case)
  • Then check for divisibility by 5 only (Buzz case)
  • If none of the above, add the number as a string to the result array

Steps to solve by this approach:

 Step 1: Initialize an empty array to store the FizzBuzz results.
 Step 2: Create a loop that iterates from 1 to n (inclusive).
 Step 3: For each number, first check if it's divisible by both 3 and 5 using modulo operator.
 Step 4: If divisible by both, add "FizzBuzz" to the result array.
 Step 5: If only divisible by 3, add "Fizz" to the result array.
 Step 6: If only divisible by 5, add "Buzz" to the result array.
 Step 7: If not divisible by either, convert the number to string and add to result array.

Submitted Code :