CodingEasy Logic Basics

FizzBuzz

Asked for all developer roles

Why they ask this: Filters out candidates who cannot write a simple loop with conditions; order of checks is the classic trap.

Problem

Return a list of strings for the numbers 1 to n where:

  • multiples of 3 become "Fizz",
  • multiples of 5 become "Buzz",
  • multiples of both 3 and 5 become "FizzBuzz",
  • every other number is the number itself as a string.

Example

text
Input:  n = 15
Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]

Hints

    Approach

    Loop from 1 to n. For each i, check i % 15 first, then i % 3, then i % 5, and otherwise use the number.

    An alternative that scales to more rules: build the word by appending "Fizz" when divisible by 3 and "Buzz" when divisible by 5, then fall back to the number if the word is empty.

    Solution

    js
    function fizzBuzz(n) {
      const result = [];
    
      for (let i = 1; i <= n; i++) {
        if (i % 15 === 0) result.push('FizzBuzz');
        else if (i % 3 === 0) result.push('Fizz');
        else if (i % 5 === 0) result.push('Buzz');
        else result.push(String(i));
      }
    
      return result;
    }
    
    console.log(fizzBuzz(15));
    Time O(n) Space O(n)

    Can you explain this in your own words?

    Back to coding practice