Fibonacci Number - Problem

The Fibonacci numbers, commonly denoted F(n), form a sequence called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1.

That is:

  • F(0) = 0
  • F(1) = 1
  • F(n) = F(n - 1) + F(n - 2), for n > 1

Given n, calculate F(n).

Input & Output

Example 1 — Small Number
$ Input: n = 2
Output: 1
💡 Note: F(2) = F(1) + F(0) = 1 + 0 = 1
Example 2 — Medium Number
$ Input: n = 3
Output: 2
💡 Note: F(3) = F(2) + F(1) = 1 + 1 = 2
Example 3 — Base Case
$ Input: n = 4
Output: 3
💡 Note: F(4) = F(3) + F(2) = 2 + 1 = 3

Constraints

  • 0 ≤ n ≤ 30

Visualization

Tap to expand
Fibonacci Number - Space-Optimized DP INPUT Fibonacci Sequence: F(0) = 0 F(1) = 1 F(2) = ? Formula: F(n) = F(n-1) + F(n-2) Input Value: n = 2 ALGORITHM STEPS 1 Initialize Variables prev2=0, prev1=1 2 Check Base Cases if n==0: return 0 if n==1: return 1 3 Iterate i=2 to n curr = prev1 + prev2 4 Update Variables prev2 = prev1 prev1 = curr For n=2: i=2: curr = 1 + 0 = 1 prev2=1, prev1=1 return prev1 = 1 FINAL RESULT Fibonacci Sequence Built: F(0) 0 F(1) 1 F(2) 1 Calculation: F(2) = F(1) + F(0) F(2) = 1 + 0 = 1 Output: 1 OK - Answer Verified Key Insight: Space-Optimized DP uses only O(1) space by keeping track of just two previous values instead of storing the entire sequence. Time complexity remains O(n) while space drops from O(n) to O(1). TutorialsPoint - Fibonacci Number | Space-Optimized DP Approach
Asked in
Google 15 Amazon 12 Facebook 8 Apple 6
172.8K Views
Medium Frequency
~15 min Avg. Time
4.8K 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