Back To Articles

[Algorithms] Fizz Buzz

🧑🏻‍💻 Sean Huang 📅 August 7, 2024

Article Image

Fizz Buzz is often the very first algorithm people learn. It's a classic and fundamental concept, serving as an entry point into algorithm learning — simple yet fun!

Problem Description

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.

Key Concept

Modulus Operator

The main tool for this algorithm is the modulus operator (%). This operator returns the remainder after division and helps us determine whether a number is divisible by another. It’s perfect for checking the conditions required in the Fizz Buzz problem.

Example Code

function fizzBuzz(num) {
  for (var i = 1; i <= num; i++) {
    if (i % 15 === 0) console.log("FizzBuzz");
    else if (i % 3 === 0) console.log("Fizz");
    else if (i % 5 === 0) console.log("Buzz");
    else console.log(i);
  }
}

fizzBuzz();

LeetCode 412. Fizz Buzz

/**
 * @param {number} n
 * @return {string[]}
 */
var fizzBuzz = function (n) {
  let res = [];

  for (let i = 1; i < n + 1; i += 1) {
    if (i % 3 === 0 && i % 5 === 0) {
      res.push("FizzBuzz");
    } else if (i % 3 === 0) {
      res.push("Fizz");
    } else if (i % 5 === 0) {
      res.push("Buzz");
    } else {
      res.push(`${i}`);
    }
  }

  return res;
};

Further Exploration

LeetCode 2525. Categorize Box According to Criteria

/**
 * @param {number} length
 * @param {number} width
 * @param {number} height
 * @param {number} mass
 * @return {string}
 */
var categorizeBox = function (length, width, height, mass) {
  let isBulky =
    length >= 10 ** 4 ||
    width >= 10 ** 4 ||
    height >= 10 ** 4 ||
    length * width * height >= 10 ** 9;
  let isHeavy = mass >= 100;

  if (isBulky && isHeavy) {
    return "Both";
  } else if (!isBulky && !isHeavy) {
    return "Neither";
  } else if (isBulky && !isHeavy) {
    return "Bulky";
  } else if (!isBulky && isHeavy) {
    return "Heavy";
  }
};

Conclusion

Fizz Buzz is a classic beginner problem that teaches basic control flow and conditional logic. It’s a great starting point for building algorithmic thinking and preparing for more complex coding challenges.