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:
- Check if the number is divisible by both 3 and 5 (using modulo operation with 15) and append "FizzBuzz".
- Else, check if it is divisible by 3 and append "Fizz".
- Else, check if it is divisible by 5 and append "Buzz".
- Otherwise, convert the number to a string and append it. This approach directly models the problem statement using conditionals and basic arithmetic operations.