<AI/>
enru
All posts

Fizz Buzz

LeetCode 412: Build an array of strings for numbers from 1 to n following the classic FizzBuzz rules.

Difficulty
Easy
Published
Topics
#math#string
Open on LeetCode

Problem Description

You are given an integer n. Write a function that takes n and returns an array of strings answer built according to the following rules:

  • answer[i] == "FizzBuzz" if i is divisible by both 3 and 5;
  • answer[i] == "Fizz" if i is divisible by 3 only;
  • answer[i] == "Buzz" if i is divisible by 5 only;
  • answer[i] == i in all other cases.

Constraints

The value of n is in the range from 1 to 104.

Examples

Input: 3

Answer: ["1","2","Fizz"]

Solution

To solve the problem, we run a loop from 1 to n and check 4 mutually exclusive conditions on each iteration. If a condition holds, we append the corresponding string to the result array.

typescript
export const fizzBuzz = (n: number): string[] => {
  const res: string[] = [];
 
  for (let i = 1; i <= n; i++) {
    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(String(i));
    }
  }
 
  return res;
};

Complexity Analysis

Time Complexity

The time complexity is linear: O(n), since we iterate from 1 to n.

Space Complexity

The space complexity is constant: O(1), since we don't create any additional variables besides the answer.