#2648

Generate Fibonacci Sequence

Easy
Two PointersDynamic Programming
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

The optimal solution uses an iterative approach to generate Fibonacci numbers, which avoids the overhead of recursion and repeated calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize two variables to store the first two Fibonacci numbers.
  2. 2Step 2: Use a loop to yield the Fibonacci numbers up to callCount.
  3. 3Step 3: Update the variables in each iteration to get the next Fibonacci number.
solution.py5 lines
1def fib_generator(call_count):
2    a, b = 0, 1
3    for _ in range(call_count):
4        yield a
5        a, b = b, a + b

Complexity note: This complexity is linear because we only loop through the numbers once, calculating each Fibonacci number in constant time.

  • 1Understanding the difference between recursive and iterative solutions is crucial.
  • 2Generators allow for efficient memory usage by yielding values one at a time.

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