Difficulty | Source | Tags | |||
---|---|---|---|---|---|
Easy |
160 Days of Problem Solving (BONUS PROBLEMS 🎁) |
|
The problem can be found at the following link: Problem Link
Given an integer n
, for every integer 1 ≤ i ≤ n
, the task is to return an array of strings where:
- "FizzBuzz" is included if
i
is divisible by both 3 and 5, - "Fizz" is included if
i
is divisible only by 3, - "Buzz" is included if
i
is divisible only by 5, - The number
i
itself is included as a string if none of the above conditions are true.
Input:
n = 3
Output:
["1", "2", "Fizz"]
Input:
n = 10
Output:
["1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz"]
Input:
n = 20
Output:
["1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz", "16", "17", "Fizz", "19", "Buzz"]
$1 ≤ n ≤ 10^6$
-
Iterate from 1 to
n
:
Loop through all integers from 1 ton
. -
Check divisibility:
- Use modulus (
%
) to check ifi
is divisible by both 3 and 5, only by 3, or only by 5. - If divisible by both 3 and 5, append
"FizzBuzz"
. - If divisible only by 3, append
"Fizz"
. - If divisible only by 5, append
"Buzz"
. - Otherwise, append the number itself as a string.
- Use modulus (
-
Store Results:
Add the computed value to the result list or array. -
Output Results:
Return the result array.
-
Time Complexity: O(n)
The algorithm iterates once through all integers from 1 ton
. Each iteration involves constant-time operations to check divisibility and string concatenation. -
Space Complexity: O(n)
The result array stores alln
strings.
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> result;
result.reserve(n);
for (int i = 1; i <= n; i++) {
string current = "";
if (i % 3 == 0) current += "Fizz";
if (i % 5 == 0) current += "Buzz";
if (current.empty()) current = to_string(i);
result.push_back(current);
}
return result;
}
};
class Solution {
public static ArrayList<String> fizzBuzz(int n) {
ArrayList<String> result = new ArrayList<>(n);
for (int i = 1; i <= n; i++) {
StringBuilder current = new StringBuilder();
if (i % 3 == 0) current.append("Fizz");
if (i % 5 == 0) current.append("Buzz");
if (current.length() == 0) current.append(i);
result.add(current.toString());
}
return result;
}
}
class Solution:
def fizzBuzz(self, n: int):
result = []
for i in range(1, n + 1):
current = []
if i % 3 == 0:
current.append("Fizz")
if i % 5 == 0:
current.append("Buzz")
if not current:
current.append(str(i))
result.append("".join(current))
return result
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐