We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Fizz Buzz

Number: 412

Difficulty: Easy

Paid? No

Companies: Amazon, IBM, Google, Microsoft, Cisco, Meta, Citadel, Cognizant, Apple, J.P. Morgan, Media.net, Bloomberg, Adobe, LinkedIn, Oracle, tcs, Cloudflare


Problem Description

Given a positive integer n, generate a 1-indexed string array of length n such that:

  • For numbers divisible by both 3 and 5, insert "FizzBuzz".
  • For numbers divisible by 3 only, insert "Fizz".
  • For numbers divisible by 5 only, insert "Buzz".
  • Otherwise, insert the number itself as a string.

Key Insights

  • Iterate from 1 to n, processing each index according to its divisibility.
  • Prioritize checking divisibility by both 3 and 5 first (i.e., by 15).
  • Use modulo operations to determine divisibility.
  • Convert numbers to strings when they do not satisfy any condition.

Space and Time Complexity

Time Complexity: O(n) - we iterate through numbers from 1 to n.
Space Complexity: O(n) - we store a string for each number in the resulting array.


Solution

We solve this problem using a simple iteration. For every number from 1 to n, we perform the following:

  1. Check if the number is divisible by both 3 and 5 (using modulo operation with 15) and append "FizzBuzz".
  2. Else, check if it is divisible by 3 and append "Fizz".
  3. Else, check if it is divisible by 5 and append "Buzz".
  4. Otherwise, convert the number to a string and append it. This approach directly models the problem statement using conditionals and basic arithmetic operations.

Code Solutions

# Python implementation of Fizz Buzz

def fizzBuzz(n):
    # Initialize the result list
    result = []
    # Loop from 1 to n (inclusive)
    for i in range(1, n + 1):
        # If divisible by both 3 and 5, append "FizzBuzz"
        if i % 3 == 0 and i % 5 == 0:
            result.append("FizzBuzz")
        # If divisible by 3, append "Fizz"
        elif i % 3 == 0:
            result.append("Fizz")
        # If divisible by 5, append "Buzz"
        elif i % 5 == 0:
            result.append("Buzz")
        # Otherwise, append the number as a string
        else:
            result.append(str(i))
    return result

# Example usage:
print(fizzBuzz(15))
← Back to All Questions