× logo Home HTML CSS Javascript React-App Angular logo
logo

Mastering Top 10 Javascript Algorithms

**Algorithm Name**: FizzBuzz Algorithm

* **Question**: What is Fizz Buzz algorithm?

* **Time Complexity**:
- Optimized: O(n)

* **Space Complexity**:
- Optimized: O(1)
* **Approaches**:

- Optimized: Loop from 1 to n and print 'Fizz' if the number is divisible by 3, 'Buzz' if the number is divisible by 5, 'FizzBuzz' if the number is divisible by both 3 and 5, else print the number.

* **Explanation**:
The FizzBuzz algorithm is a common programming task, used in interviews to weed out non-programmers during hiring process. It is asked to write a program that prints the numbers from 1 to n. But for multiples of three, print "Fizz" instead of the number, and for multiples of five, print "Buzz". For numbers which are multiples of both three and five, print "FizzBuzz".

* **Sample Code**:javascript

const fizzBuzz = (n) => {
for(let i = 1; i <= n; i++) {

// Check if the number is a multiple of 3 and 5
if(i % 3 === 0 && i % 5 === 0) {
console.log('FizzBuzz');
}

// Check if the number is a multiple of 3
else if(i % 3 === 0) {
console.log('Fizz');
}

// Check if the number is a multiple of 5
else if(i % 5 === 0) {
console.log('Buzz');
}
else {
console.log(i);
}
}
}

* **Example**:
//Unit Test
console.log(fizzBuzz(15));
- Input: `fizzBuzz(15)`
- Output: The program prints the following:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

This is because 'Fizz' replaces multiples of 3, 'Buzz' replaces multiples of 5, and 'FizzBuzz' replaces multiples of



logo