2648. Generate Fibonacci Sequence
Explanation
To generate the Fibonacci sequence, we can create a generator function that yields the Fibonacci numbers one by one. We can use a while loop inside the generator function to calculate the next Fibonacci number based on the previous two numbers. The generator function will keep track of the current and previous Fibonacci numbers.
Algorithm:
- Create a generator function
fibGenerator
that initializesprev
andcurr
to 0 and 1 respectively. - Yield the first Fibonacci number which is 0.
- Use a while loop that runs
callCount
times to generate the next Fibonacci numbers. - Calculate the next Fibonacci number as the sum of
prev
andcurr
. - Update
prev
andcurr
with the current values and yield the new Fibonacci number. - Repeat steps 4-5 for
callCount
iterations.
Time Complexity:
The time complexity of generating the Fibonacci sequence is O(n), where n is the callCount
.
Space Complexity:
The space complexity of the generator function is O(1) as we are only storing the previous and current Fibonacci numbers.
import java.util.Iterator;
public class FibonacciGenerator implements Iterator<Integer> {
private int prev = 0;
private int curr = 1;
private int count = 0;
@Override
public boolean hasNext() {
return true;
}
@Override
public Integer next() {
if (count == 0) {
count++;
return prev;
}
int next = prev + curr;
prev = curr;
curr = next;
count++;
return prev;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.