LeetCode Problem Workspace
Generate Fibonacci Sequence
Implement a generator that produces the Fibonacci sequence up to a specified number of elements efficiently in JavaScript.
0
Topics
1
Code langs
0
Related
Practice Focus
Easy · Generate Fibonacci Sequence core interview pattern
Answer-first summary
Implement a generator that produces the Fibonacci sequence up to a specified number of elements efficiently in JavaScript.
Ace coding interviews with Interview AiBoxInterview AiBox guidance for Generate Fibonacci Sequence core interview pattern
Start by returning a generator function that yields each Fibonacci number on demand. Initialize the sequence with 0 and 1, then use a loop or recursive yield to generate subsequent values. This approach ensures O(N) time complexity and preserves state correctly across calls, matching the generate Fibonacci sequence core interview pattern.
Problem Statement
Write a JavaScript generator function named fibGenerator that yields numbers in the Fibonacci sequence sequentially. The generator should start with 0 and 1, then produce the next number as the sum of the previous two, allowing repeated calls to next() to retrieve values one at a time.
Given an integer callCount, return an array of the first callCount Fibonacci numbers produced by the generator. Ensure the implementation handles callCount values from 0 up to 50 and maintains the proper sequence order without precomputing the entire series.
Examples
Example 1
Input: callCount = 5
Output: [0,1,1,2,3]
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: []
gen.next() is never called so nothing is outputted
Constraints
- 0 <= callCount <= 50
Solution Approach
Initialize the first two Fibonacci numbers
Start the generator by defining two variables representing the first two numbers: 0 and 1. Yield these immediately for the initial calls.
Iteratively generate subsequent numbers
Use a loop to calculate each next Fibonacci number by summing the previous two numbers. Yield each computed value so the generator maintains the sequence state correctly.
Handle callCount efficiently
Collect the results in an array by calling next() repeatedly up to callCount times. This ensures O(N) time and space without generating unused values or storing excessive state.
Complexity Analysis
| Metric | Value |
|---|---|
| Time | O(N) |
| Space | O(N) |
Time complexity is O(N) because each Fibonacci number up to callCount is generated once. Space complexity is O(N) for storing the resulting array, while the generator itself maintains constant extra memory for the last two numbers.
What Interviewers Usually Probe
- Check if the candidate correctly uses JavaScript generator syntax for lazy evaluation.
- Notice if the candidate handles callCount = 0 without producing any output.
- Look for proper state management to yield each Fibonacci number sequentially without precomputing the entire sequence.
Common Pitfalls or Variants
Common pitfalls
- Returning an array instead of a generator breaks the lazy generation pattern.
- Incorrectly updating the previous two numbers can produce the wrong Fibonacci sequence.
- Not handling callCount = 0 or edge values up to 50 can cause errors or extra iterations.
Follow-up variants
- Generate Fibonacci sequence recursively using a generator function.
- Yield only even Fibonacci numbers up to callCount.
- Implement a generator that supports negative Fibonacci indices as well.
FAQ
What is the simplest way to generate Fibonacci numbers in JavaScript?
Using a generator function allows you to yield each Fibonacci number on demand without precomputing the full sequence.
How does the generator maintain state between calls?
The generator keeps local variables for the last two numbers, updating them on each yield to produce the next Fibonacci number correctly.
Can I handle callCount larger than 50?
While the generator itself supports larger values, the problem constraints limit callCount to 50 to ensure predictable performance in interviews.
Why use a generator instead of a simple loop?
Generators implement the generate Fibonacci sequence core interview pattern by lazily yielding values, which is preferred in interviews for stateful iteration.
How do I retrieve the first N Fibonacci numbers using fibGenerator?
Initialize the generator, then call next() repeatedly N times, collecting each value into an array to produce the required sequence.
Solution
Solution 1
#### TypeScript
function* fibGenerator(): Generator<number, any, number> {
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
*/