Generate Fibonacci Sequence Problem
Problem
Write a generator function that returns a generator object which yields the fibonacci sequence.
The fibonacci sequence is defined by the relation Xn = Xn-1 + Xn-2
.
The first few numbers of the series are 0, 1, 1, 2, 3, 5, 8, 13
.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 – Generator Function with State Variables
Intuition
A generator function can maintain its own state between calls. For the Fibonacci sequence, we only need to remember the last two numbers to generate the next one. By yielding each value and updating the state, we can produce the sequence indefinitely.
Approach
- Initialize two variables,
a
andb
, to 0 and 1 (the first two Fibonacci numbers). - Use an infinite loop to yield
a
and updatea
andb
to the next Fibonacci numbers. - Each call to
.next()
on the generator will yield the next Fibonacci number.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(1)
per call to.next()
, since only a constant number of operations are performed for each value. - 🧺 Space complexity:
O(1)
, as only two variables are maintained regardless of how many numbers are generated.