Fizz Buzz | LeetCode in C#
How I solved LeetCode's Fizz Buzz problem in C#
The Fizz Buzz problem is a classic exercise that is often used to teach basic programming concepts such as loops and conditionals.
In this article, I’ll show you my attempt to solve this problem.
Problem Description
Given an integer n
, return a string array answer
(1-indexed) where:
answer[i] == "FizzBuzz"
ifi
is divisible by3
and5
.answer[i] == "Fizz"
ifi
is divisible by3
.answer[i] == "Buzz"
ifi
is divisible by5
.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
Intuition
When breaking down the problem, the task is to iterate through a sequence of numbers while applying simple divisibility rules to determine the correct output for each number.
The logic is straightforward: replace numbers with specific words based on their divisibility.
Approach
To solve the Fizz Buzz problem, we can use a simple loop and a series of conditional checks:
- Initialize a List: Start by creating a list to store the results.
- Iterate through Numbers: Loop through numbers from 1 to
n
. - Check Divisibility:
- If a number is divisible by both 3 and 5, it should be labeled “FizzBuzz”.
- Else, if it’s divisible by 3, label it “Fizz”.
- Else, if it’s divisible by 5, label it “Buzz”.
- If none of these conditions are met, add the number itself as a string.
- Add to List: For each number, append the appropriate label or number to the results list.
- Return the Result: Finally, return the list containing all the strings.
Complexity
-
Time complexity: The time complexity is \(O(n)\) because we process each number from 1 to
n
exactly once. -
Space complexity: The space complexity is \(O(n)\) because we store a string result for each number in the input range.
Code
Video
Conclusion
This approach provides an efficient way to implement the Fizz Buzz logic by using a loop and conditional checks.
The function generates the desired output for any valid positive integer n
, allowing it to handle a wide range of input values effectively.
This solution is not only concise but also clear, making it easy to understand for anyone familiar with basic programming constructs.
This explanation captures the essence of how the Fizz Buzz problem can be addressed programmatically with a simple and clean loop-and-conditional structure.