Taro Logo

Fizz Buzz

Easy
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+16
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
849 views
Topics:
ArraysStrings

Given an integer n, return a string array answer (1-indexed) where:

  • answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
  • answer[i] == "Fizz" if i is divisible by 3.
  • answer[i] == "Buzz" if i is divisible by 5.
  • answer[i] == i (as a string) if none of the above conditions are true.

Example 1:

Input: n = 3
Output: ["1","2","Fizz"]

Example 2:

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

Example 3:

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

Constraints:

  • 1 <= n <= 104

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the expected upper bound for the integer $n$, and could $n$ be less than 1?
  2. Should the returned array be 1-indexed (matching the problem description) or 0-indexed?
  3. What data type should the elements in the returned array be? Are they strictly strings?
  4. Should numbers that are not divisible by 3 or 5 be converted to strings using standard formatting?
  5. How should the solution handle extremely large values of $n$ in terms of memory allocation for the resulting array?

Brute Force Solution

Approach

Imagine you have a row of consecutive numbered boxes starting from one up to a given ending number. The brute force strategy involves walking through every single box one by one, looking at its number, and writing down the correct answer on a notepad based on simple counting rules.

Here's how the algorithm would work step-by-step:

  1. Begin at the very first box and look at the number written inside it.
  2. Check if that number can be cleanly divided by three and also by five at the same time.
  3. If it can be divided by both, write down a special combined word on your notepad.
  4. If it cannot be divided by both, check if it can be divided by just three, and if so, write down the first special word.
  5. If it cannot be divided by three, check if it can be divided by five, and if so, write down the second special word.
  6. If the number does not meet any of these special division tests, simply write down the number itself on your notepad.
  7. Move on to the next box in line and repeat this exact same checking process until you have visited every single box.

Code Implementation

def fizz_buzz(ending_number):
    notepad_results = []

    for current_number in range(1, ending_number + 1):
        # Check both divisibility conditions first to capture multi-ples of fifteen
        if current_number % 3 == 0 and current_number % 5 == 0:
            notepad_results.append("FizzBuzz")

        # Check divisibility by three alone before falling back to other rules
        elif current_number % 3 == 0:
            notepad_results.append("Fizz")

        # Check divisibility by five alone since it failed previous strict tests
        elif current_number % 5 == 0:
            notepad_results.append("Buzz")

        # Default fallback to record the raw number when no rules apply
        else:
            notepad_results.append(str(current_number))

    return notepad_results

Big(O) Analysis

Time Complexity
O(n) – To solve the Fizz Buzz problem, we iterate through a single loop from one up to the given input size n. During each iteration for every box in line, we perform a constant number of arithmetic modulo operations and string conversions. Because we visit each of the n numbers exactly once and perform a fixed amount of work per number, the total operations scale linearly with n. This results in an overall runtime complexity of O(n).
Space Complexity
O(N) – To satisfy the requirements described in the plain English steps, the algorithm must maintain a resulting list of strings to record the answers for all consecutive boxes. As we iterate from one up to the ending number N, we continuously append items to this collection. Therefore, the extra memory required scales linearly with the input size N to hold the final output of results.

Optimal Solution

Approach

The optimal strategy is to go through a sequence of numbers one by one, deciding what to say based on whether the number is a multiple of certain special values. Instead of doing complicated math, we just check each number individually and write down the correct word or the number itself.

Here's how the algorithm would work step-by-step:

  1. Begin at the first number in the sequence and look at it closely.
  2. Check if the number is a multiple of both special values at the same time.
  3. If it is a multiple of both, write down the combined special word for that number.
  4. If it is not a multiple of both, check if it is just a multiple of the first special value.
  5. If it is a multiple of the first special value, write down that specific word.
  6. If it is not, check if it is a multiple of the second special value.
  7. If it is a multiple of the second special value, write down that specific word.
  8. If the number is not a multiple of any of the special values, simply write down the number itself as a word.
  9. Move on to the next number in the sequence and repeat these checks until you reach the end.

Code Implementation

def fizz_buzz(upper_limit):
    result_sequence = []
    
    for current_number in range(1, upper_limit + 1):
        # Checking both conditions first prevents missing numbers that need the combined word.
        if current_number % 3 == 0 and current_number % 5 == 0:
            result_sequence.append("FizzBuzz")
        elif current_number % 3 == 0:
            result_sequence.append("Fizz")
        # Checking the second condition independently ensures multiples of five are properly labeled.
        elif current_number % 5 == 0:
            result_sequence.append("Buzz")
        else:
            result_sequence.append(str(current_number))
            
    # Returning the fully populated sequence satisfies the output requirement for the caller.
    return result_sequence

Big(O) Analysis

Time Complexity
O(n) – To solve this problem, we iterate through a sequence from 1 to n once, performing a constant number of arithmetic checks for each number. As we visit each of the n elements, we evaluate divisibility and append the corresponding result to our output list. The total work scales directly with the input size n, resulting in approximately 4n individual check operations. Simplifying this linear progression leaves us with a final runtime complexity of O(n).
Space Complexity
O(N) – The algorithm allocates a single result list to store the sequence of strings from 1 to N. As the input size N increases, the number of string elements appended to this output list grows linearly. Therefore, the auxiliary space complexity is directly proportional to the size of the input sequence.

Edge Cases

Input n equals 1
How to Handle:
The loop runs once and returns a single-element array containing the string "1".
Inputs less than 1 such as zero or negative integers
How to Handle:
The problem constraints typically specify n >= 1, but if encountered, return an empty array.
Maximum-sized inputs like n equals 10 to the 4th or 10 to the 5th power
How to Handle:
The linear time O(n) approach ensures the algorithm executes well within time limits without performance degradation.
Memory limits with large n values
How to Handle:
Pre-allocating the resulting array of strings prevents dynamic resizing overhead and memory fragmentation.
Numbers that are multiples of both 3 and 5
How to Handle:
Checking divisibility by 15 or both 3 and 5 first prevents premature matching of "Fizz" or "Buzz".
Language-specific integer overflow
How to Handle:
Standard 32-bit or 64-bit integers easily accommodate typical interview constraints for n without overflow risks.