#412

Fizz Buzz

Easy
MathStringSimulationString manipulationConditional statements
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution is actually the same as the brute force approach in terms of logic, but we can optimize our checks by using a single loop and directly appending results based on the conditions. This is efficient and clear.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an empty list to store the results.
  2. 2Step 2: Loop through each number from 1 to n.
  3. 3Step 3: Use a single conditional statement to check if the number is divisible by both 3 and 5, then check for 3, then for 5, and finally append the number if none match.
  4. 4Step 4: Return the results list.
solution.py10 lines
1def fizzBuzz(n):
2    result = []
3    for i in range(1, n + 1):
4        output = ''
5        if i % 3 == 0:
6            output += 'Fizz'
7        if i % 5 == 0:
8            output += 'Buzz'
9        result.append(output or str(i))
10    return result

Complexity note: The time complexity remains O(n) as we still iterate through all numbers from 1 to n. The space complexity is O(n) since we store n results in the output list.

  • 1Understanding divisibility is crucial for this problem.
  • 2Using string concatenation can simplify the logic.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.