OneBite.Dev - Coding blog in a bite size

fizz buzz program sample in javascript

The FizzBuzz problem is a classic coding interview question. Here is sample program and how to solve it

The FizzBuzz problem is a classic coding interview question. The problem is defined as follows:

For numbers 1 through n, print “Fizz” for multiples of 3, “Buzz” for multiples of 5, and “FizzBuzz” for multiples of both 3 and 5. If the number is not a multiple of either 3 or 5, print the number.

Here’s a simple and efficient implementation of FizzBuzz in JavaScript:

function fizzBuzz(n) {
  for(let i = 1; i <= n; i++) {
    let output = '';

    if(i % 3 === 0) {
      output += 'Fizz';
    }

    if(i % 5 === 0) {
      output += 'Buzz';
    }

    console.log(output || i);
  }
}

fizzBuzz(100);

Explanation

This function iterates from 1 to n (inclusive). For each number, it builds a string output. If the number is a multiple of 3, it appends ‘Fizz’ to output.

If the number is a multiple of 5, it appends ‘Buzz’ to output. If output is an empty string (meaning the number is not a multiple of 3 or 5), it defaults to printing the number itself.

This is done using the || operator: output || i will evaluate to i if output is an empty string, which is considered a falsy value in JavaScript.

Time Complexity Info

In terms of time complexity, this solution is O(n), where n is the input to the fizzBuzz function. It must iterate over each number from 1 to n once, and the operations inside the loop (modulus calculation, string concatenation, and console logging) can all be done in constant time. Therefore, this solution is very efficient.

← How to find the maximum c...
Chunking array buy n numb... →
javascript