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.
Example 1:
Input: callCount = 5 Output: [0,1,1,2,3] Explanation: const gen = fibGenerator(); gen.next().value; // 0 gen.next().value; // 1 gen.next().value; // 1 gen.next().value; // 2 gen.next().value; // 3
Example 2:
Input: callCount = 0 Output: [] Explanation: gen.next() is never called so nothing is outputted
Constraints:
0 <= callCount <= 50This approach uses an iterative method to generate Fibonacci numbers. The idea is to maintain two variables representing the last two numbers in the sequence and update them in each iteration.
This code defines a generator function fib_generator() which yields Fibonacci numbers indefinitely. It initializes two variables a and b to 0 and 1 (first two Fibonacci numbers) and then enters an infinite loop where it yields a and updates a, b to the next two numbers in the sequence.
JavaScript
Time Complexity: O(1) per yield.
Space Complexity: O(1).
This approach uses recursion to generate Fibonacci numbers. This approach is more intuitive but is less common due to the overhead of recursive calls.
This C++ solution emulates generator behavior using a class called Fibonacci. The class maintains state between calls using private member variables a and b, similar to static variables in a recursive function. The function next() returns the next Fibonacci number.
C#
Time Complexity: O(1) per call.
Space Complexity: O(1).
| Approach | Complexity |
|---|---|
| Approach 1: Iterative Generator | Time Complexity: O(1) per yield. |
| Approach 2: Recursive Generator | Time Complexity: O(1) per call. |
Noob Recursive Backtracker vs Dynamic Programming Tabulator • Greg Hogg • 1,290,384 views views
Watch 9 more video solutions →Practice Generate Fibonacci Sequence with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor