Generate Fibonacci Sequence - Problem

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...

Your generator should yield numbers indefinitely when called repeatedly.

Input & Output

Example 1 — First 6 Numbers
$ Input: n = 6
Output: [0,1,1,2,3,5]
💡 Note: The first 6 Fibonacci numbers: F(0)=0, F(1)=1, F(2)=0+1=1, F(3)=1+1=2, F(4)=1+2=3, F(5)=2+3=5
Example 2 — First 8 Numbers
$ Input: n = 8
Output: [0,1,1,2,3,5,8,13]
💡 Note: Extending further: F(6)=3+5=8, F(7)=5+8=13. Each number is sum of previous two.
Example 3 — Edge Case
$ Input: n = 1
Output: [0]
💡 Note: Only the first Fibonacci number, which is 0 by definition.

Constraints

  • 1 ≤ n ≤ 50
  • Generated numbers will fit in 64-bit integer

Visualization

Tap to expand
Generate Fibonacci Sequence INPUT n = 6 (number of values) Generator Function function* fibonacci() yields values indefinitely Fibonacci Formula: Xn = Xn-1 + Xn-2 Starting: X0=0, X1=1 0, 1, 1, 2, 3, 5, 8, 13... ALGORITHM STEPS 1 Initialize Set a=0, b=1 2 Yield Current yield a (current value) 3 Update Values [a, b] = [b, a+b] 4 Loop Forever Repeat steps 2-3 Iteration Trace: i a b yield 0 0 1 0 1 1 1 1 2 1 2 1 3 2 3 2 ... ... ... ... FINAL RESULT First 6 Fibonacci Numbers: 0 [0] 1 [1] 1 [2] 2 [3] 3 [4] 5 [5] Output Array: [0,1,1,2,3,5] OK - Complete! Generator can continue yielding: 8, 13, 21... Key Insight: Generators use yield to pause and resume, maintaining state between calls. This allows infinite sequences with O(1) space - only storing current (a) and next (b) values. Time Complexity: O(n) per n values | Space Complexity: O(1) constant TutorialsPoint - Generate Fibonacci Sequence | Iterative Generator Approach
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 6
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen