All Articles

FizzBuzz Coding Interview Question

inner peace

Recently I watched this video from Tom Scott’s Youtube Channel. I highly encourage you to go and check that video and a huge shout-out to Tom Scott (You can follow him on Twitter)

I will add my self-note in here. Maybe it will help you to improve your coding skills. You can take some time and do it yourself. Then check how much of your answer is tally with this answer.

For the start maybe you can add some comments as what you are going to do or what you need to do.

A quick introduction for Fizz Buzz question. Given 1 to 100, if a number is a divide by 3 print Fizz if a number is a divide by 5, print Buzz, if the number is divide by both, print FizzBuzz, else print the number.

Starting from here I will give some code blocks and explains how to improve it.

Okay, let’s consider the below example.

// I need a for loop in here
// inside that check the number divide by 3
// if so print Fizz

// if number is divide by 5 print Buzz

// if number is divide by 3 and 5, print FizzBuzz

// else print the number

for (let i = 1; i <= 100; i++) {
  if (i % 5 === 0 && i % 3 === 0) {
    console.log("FizzBuzz");
  } else if (i % 3 === 0) {
    console.log("Fizz");
  } else if (i % 5 === 0) {
    console.log("Buzz");
  } else {
    console.log(i);
  }
}

This is a perfectly fine code. The point that I need to highlight in here, that we wrote some test 2 times. We checked that number is divided by 5, two times and number is divided by 3. If we need to change 5 to 8, we need to change 2 times. So there is some room to improve.

So, let’s consider below code.

for (let i = 1; i <= 100; i++) {
  let output = "";
  if (i % 3 === 0) {
    output += "Fizz";
  }
  if (i % 5 === 0) {
    output += "Buzz";
  }
  if (output === "") {
    output += i;
  }
  console.log(output);
}

This is great because of a few reasons. We are not repeating our checks. If we want to change some value we can do it from one place. We detach the else block. Also if we want more checks just add below line.

if (i % [number] === 0) {
  output += "Word_You_Need";
}

Also, we reduce the console.log to one line.

But you can argue that we are repeating some code line over and over again. To avoid that adding a method. But this point I think you already impressed the interviewer.

If you have anything to ask regarding this please leave a comment here. Also, I wrote this according to my understanding. So if any point is wrong, don’t hesitate to correct me. I really appreciate you.

That’s for today friends. See you soon. Thank you

Main image credit