Fibonacci Number
Easy
Topics
The Fibonacci numbers satisfy F(0)=0, F(1)=1, and F(n)=F(n-1)+F(n-2) for n > 1. Given n, return F(n).
Example 1
Index
i holds F(i), each the sum of its two neighbours to the left. F(2) = 1.Cell index is
i, cell value is F(i).Input: n = 2 Output: 1
Example 2
Input: n = 4 Output: 3
Constraints
- 0 <= n <= 30
Editorial — intuition, approach, complexity and pitfalls
Intuition
Naive recursion recomputes the same subproblems exponentially. Since F(n) depends only on the previous two values, iterate and keep just those two.
Approach
- Return n directly for F(0)=0 and F(1)=1.
- Otherwise roll two variables forward n-1 times.
- Return the second.
Walkthrough
n = 6
0, 1, 1, 2, 3, 5, 8 -> F(6) = 8Complexity
- Time — O(n): one loop.
- Space — O(1): two rolling variables (vs. O(n) for memoized recursion).
Common Pitfalls
- The base case is
n < 2, notn <= 2. F(2) is 1 and gets computed by the loop; short-circuiting it returns 2. - Two variables are enough. The recursive form without memoisation is O(2^n) and recomputes F(5) dozens of times for F(30), which is the thing the problem exists to show.
Full Solution — all languages
class Solution:
def fib(self, n):
if n < 2:
return n
prev, cur = 0, 1
for _ in range(2, n + 1):
prev, cur = cur, prev + cur
return curimport java.util.*;
class Solution {
public int fib(int n) {
if (n < 2) return n;
long prev = 0, cur = 1;
for (int i = 2; i <= n; i++) {
long next = prev + cur;
prev = cur;
cur = next;
}
return (int) cur;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int fib(int n) {
if (n < 2) return n;
long long prev = 0, cur = 1;
for (int i = 2; i <= n; i++) {
long long next = prev + cur;
prev = cur;
cur = next;
}
return (int)cur;
}
};/**
* @param {number} n
* @return {number}
*/ var fib = function(n) {
if (n < 2) return n;
let prev = 0, cur = 1;
for (let i = 2; i <= n; i++) {
const next = prev + cur;
prev = cur;
cur = next;
}
return cur;
};