Talentd
FleetCode

2648. Generate Fibonacci Sequence

Easy83.6% acceptance2 companies

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 <= 50

Asked at 2 companies

Hints open one at a time

Hint 1
Javascript has the concept of generators. They are critical to this problem.
Hint 2
First yield 0 and 1.
Hint 3
Create an infinite "while(true)" loop.
Hint 4
In that loop, continuously yield the next value which is the sum of the previous two.
5:50
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1/**
2 * @return {Generator<number>}
3 */
4var fibGenerator = function*() {
5
6};
7
8/**
9 * const gen = fibGenerator();
10 * gen.next().value; // 0
11 * gen.next().value; // 1
12 */
Starter codeJavaScriptSpaces: 4
Examples
Input
5
Input
0
Your code is saved on this device.Solution