All coding questions

Fizz Buzz

easy
HackerRankCodeSignalmathstrings

Problem

Given a number n, return the sequence from one to n where multiples of three become Fizz, multiples of five become Buzz, multiples of both become FizzBuzz, and all other numbers stay as their string form.

Examples

Input: n = 5
Output: ["1", "2", "Fizz", "4", "Buzz"]
Three maps to Fizz and five maps to Buzz.

Constraints

  • 1 <= n <= 10^4
Hints(tap to reveal)
  • 1. Check divisibility by fifteen first.
  • 2. Otherwise test three, then five, then default.
Optimal approach(spoiler)
  1. Loop from one through n.
  2. Append FizzBuzz when divisible by both three and five.
  3. Otherwise append Fizz or Buzz for the single divisors.
  4. Fall back to the number as a string.
  5. O(n) time, O(n) output space.

Ready to solve it?

Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.

Practice in the editor