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

Easy

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:

  1. Create a generator function fibGenerator that initializes prev and curr to 0 and 1 respectively.
  2. Yield the first Fibonacci number which is 0.
  3. Use a while loop that runs callCount times to generate the next Fibonacci numbers.
  4. Calculate the next Fibonacci number as the sum of prev and curr.
  5. Update prev and curr with the current values and yield the new Fibonacci number.
  6. 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.

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.

Back to LeetCode Solutions