Katkat

Implement FizzBuzz

UberData Scientist · Onsite

Last updated

This problem tests foundational programming skills by requiring the implementation of conditional logic and string manipulation based on modular arithmetic patterns.

Problem Statement

Write a function fizz_buzz(n: int) -> list[str] that returns a list of strings representing the numbers from 1 to n (inclusive), subject to the following rules:

  1. If a number is divisible by 3, replace it with "Fizz".
  2. If a number is divisible by 5, replace it with "Buzz".
  3. If a number is divisible by both 3 and 5, replace it with "FizzBuzz".
  4. For all other numbers, return the number as a string.

Constraints

  • 1 <= n <= 10^4
  • Your solution should run in O(n) time complexity.

Example 1

Input: n = 5 Output: ["1", "2", "Fizz", "4", "Buzz"]

Example 2

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

Edge Cases

  • Consider the behavior when n = 1.
  • Ensure the order of conditional checks handles the intersection (divisibility by 15) correctly before individual checks.

Hints

Hint 1

Use the modulo operator (%) to check if a number is divisible by another integer.

Hint 2

Order your conditional statements carefully; checking for divisibility by 15 first avoids the issue of printing "Fizz" or "Buzz" prematurely.

Hint 3

Instead of hardcoding multiple `if-else` blocks, consider concatenating strings based on divisibility checks to make the code more extensible.

Follow-up questions

  • How would you modify your solution if the rules changed to include a new requirement, such as printing "Jazz" for multiples of 7?
  • Can you rewrite the function using a dictionary or a list of tuples to map divisors to strings, making it easier to add new rules without changing the core logic?
  • What is the time and space complexity of your solution, and can you explain how it scales as `n` grows?