algoadvance

You are tasked with writing an algorithm to solve the “Fizz Buzz” problem. Given an integer n, return a string array answer (1-indexed) where:

Example:

Input: n = 15

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

Clarifying Questions

  1. Range of n: What is the range of the input integer n?
    • Typically, 1 <= n <= 10^4.
  2. Edge Cases: Should we consider edge cases where n is the smallest possible value (i.e., n = 1)?
    • Yes, we should ensure the solution works for the minimum value of n.

Strategy

The strategy is straightforward:

  1. We will iterate from 1 to n, and for each number:
    • If it is divisible by both 3 and 5, we add “FizzBuzz” to the list.
    • If it is divisible by only 3, we add “Fizz” to the list.
    • If it is divisible by only 5, we add “Buzz” to the list.
    • Otherwise, we add the number itself (converted to string).

Implementation Steps:

  1. Initialize an empty list answer to store the result.
  2. Loop from 1 to n (both inclusive).
  3. For each i in this range, use conditional checks to determine the appropriate string to append to the list.
  4. Return the populated list answer at the end.

Code

def fizzBuzz(n: int):
    answer = []

    for i in range(1, n + 1):
        if i % 3 == 0 and i % 5 == 0:
            answer.append("FizzBuzz")
        elif i % 3 == 0:
            answer.append("Fizz")
        elif i % 5 == 0:
            answer.append("Buzz")
        else:
            answer.append(str(i))
    
    return answer

# Example Usage
n = 15
print(fizzBuzz(n))  # Output: ["1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz"]

Time Complexity

This concludes the solution for the Fizz Buzz problem using a simple and efficient algorithm.

Try our interview co-pilot at AlgoAdvance.com