Fibonacci Number — Solution in Python, Java & C++
Fibonacci Number solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem, asked at Amazon and TCS.
Fibonacci Number is an easy coding problem on dynamic programming, math and recursion, asked in Amazon, TCS, Infosys and Wipro interviews.
- Difficulty: Easy
- Topics: Dynamic Programming, Math, Recursion
- Asked at: Amazon, TCS, Infosys, Wipro, Accenture, Spotify, Virtusa, Tech Mahindra
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
The Fibonacci numbers form the sequence F where each number is the sum of the two before it, starting from 0 and 1:
F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2) for n > 1
Given n, calculate F(n).
Example 1
Input: n = 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
Example 2
Input: n = 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
Example 3
Input: n = 0
Output: 0
Constraints
0 <= n <= 46The answer fits in a signed 32-bit integer.
Follow-up: The naive recursion is O(2^n). Can you answer in O(n) time and O(1) space?
Hints for Fibonacci Number
Hint 1
Plain recursion recomputes the same F(k) exponentially many times.
Hint 2
Only the last two values ever matter, so carry them in two variables and slide forward.
Hint 3
Start with a = F(0) = 0 and b = F(1) = 1, then repeat
(a, b) = (b, a + b)exactly n times.
How to solve Fibonacci Number
Only the last two Fibonacci values matter for the next, so keep them in two variables and slide the pair forward n times.
Approach
- Start
a = F(0) = 0,b = F(1) = 1. - Repeat
ntimes:(a, b) = (b, a + b). - Return
a.
Why it works
After k iterations the pair holds (F(k), F(k+1)) — true at k = 0, and each step advances it by the recurrence. Naive recursion recomputes the same subproblems exponentially many times; the sliding pair is the bottom-up DP with its table compressed to two cells.
Complexity
- Time —
O(n) - Space —
O(1)
Pitfalls
- Returning
binstead ofagivesF(n+1). - Memoised recursion is also linear but risks stack depth for large
n.
Reference solution
Python
def fib(n: int) -> int:
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return aJava
public static int fib(int n) {
int a = 0, b = 1;
for (int i = 0; i < n; i++) {
int next = a + b;
a = b;
b = next;
}
return a;
}C++
int fib(int n) {
long long a = 0, b = 1;
for (int i = 0; i < n; i++) {
long long next = a + b;
a = b;
b = next;
}
return (int) a;
}JavaScript
var fib = function(n) {
let a = 0, b = 1;
for (let i = 0; i < n; i++) {
const next = a + b;
a = b;
b = next;
}
return a;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 402 dynamic programming problems · the whole catalogue
Learn the technique: Dynamic Programming · Recursion