Nth Fibonacci Number
EasyThe Fibonacci numbers are defined as F(0)=0, F(1)=1, and F(n)=F(n-1)+F(n-2) for n>=2. Given n, return F(n).
Examples
| Input | Output |
|---|---|
| n = 2 | 1 |
| n = 4 | 3 |
Python Solution
def fib(n: int) -> int:
if n <= 1:
return n
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
return bJavaScript Solution
function fib(n) {
if (n <= 1) return n;
let a = 0, b = 1;
for (let i = 2; i <= n; i++) {
[a, b] = [b, a + b];
}
return b;
}Step-by-Step Explanation
- Iterative approach: only need the last two values.
- Start with a=0, b=1. Each step: a becomes b, b becomes a+b.
- After n-1 iterations, b holds F(n).
Complexity Analysis
| Time | O(n) |
| Space | O(1) |
Tags
MathDynamic Programming
Related Problems
All Problems
Two SumReverse a StringPalindrome CheckFizzBuzzBinary SearchReverse Linked ListMerge Two Sorted ArraysValid ParenthesesMaximum Subarray (Kadane's Algorithm)Remove Duplicates from Sorted ArrayValid AnagramFirst Unique CharacterClimbing StairsRoman to IntegerBest Time to Buy and Sell StockContains DuplicateMove ZeroesIntersection of Two ArraysLongest Common Prefix