Generate Fibonacci Sequence Problem
#2648
Description
LeetCode Problem 2648.
Write a generator function that returns a generator object which yields the fibonacci sequence.
The fibonacci sequence is defined by the relation X_n = X_(n-1) + X_(n-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 <= 50
Solution
Approach: Generator with two running values
A generator can run forever because it only produces the next value when asked. Keep the last two numbers a = 0 and b = 1. Loop forever: yield a, then move the pair forward with [a, b] = [b, a + b]. The first yields are 0, 1, 1, 2, 3, ....
Nothing is computed ahead of time, and calling next() zero times does no work, matching the empty output when callCount = 0.
Complexity: O(1) time and space per next() call.
/**
* @return {Generator<number>}
*/
var fibGenerator = function* () {
let a = 0;
let b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
};
/**
* const gen = fibGenerator();
* gen.next().value // 0
* gen.next().value // 1
*/