LeetCode 2648: Generate Fibonacci Sequence Solution
Master LeetCode problem 2648 (Generate Fibonacci Sequence), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2648. Generate Fibonacci Sequence
Problem Explanation
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
fibGeneratorthat initializesprevandcurrto 0 and 1 respectively. - Yield the first Fibonacci number which is 0.
- Use a while loop that runs
callCounttimes to generate the next Fibonacci numbers. - Calculate the next Fibonacci number as the sum of
prevandcurr. - Update
prevandcurrwith the current values and yield the new Fibonacci number. - Repeat steps 4-5 for
callCountiterations.
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.
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Frequently Asked Questions
How to solve LeetCode 2648 (Generate Fibonacci Sequence)?
This page provides optimized solutions for LeetCode problem 2648 (Generate Fibonacci Sequence) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2648 (Generate Fibonacci Sequence)?
The time complexity for LeetCode 2648 (Generate Fibonacci Sequence) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2648 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2648 in Java, C++, or Python.