509. Fibonacci Number LeetCode Solution
In this guide, you will get 509. Fibonacci Number LeetCode Solution with the best time and space complexity. The solution to Fibonacci Number problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Fibonacci Number solution in C++
- Fibonacci Number solution in Java
- Fibonacci Number solution in Python
- Additional Resources
Problem Statement of Fibonacci Number
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).
Example 1:
Input: n = 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
Example 2:
Input: n = 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
Example 3:
Input: n = 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
Constraints:
0 <= n <= 30
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
509. Fibonacci Number LeetCode Solution in C++
class Solution {
public:
int fib(int n) {
if (n < 2)
return n;
vector<int> dp{0, 0, 1};
for (int i = 2; i <= n; ++i) {
dp[0] = dp[1];
dp[1] = dp[2];
dp[2] = dp[0] + dp[1];
}
return dp.back();
}
};
/* code provided by PROGIEZ */
509. Fibonacci Number LeetCode Solution in Java
class Solution {
public int fib(int n) {
if (n < 2)
return n;
int[] dp = {0, 0, 1};
for (int i = 2; i <= n; ++i) {
dp[0] = dp[1];
dp[1] = dp[2];
dp[2] = dp[0] + dp[1];
}
return dp[2];
}
}
// code provided by PROGIEZ
509. Fibonacci Number LeetCode Solution in Python
class Solution:
def fib(self, n: int) -> int:
if n < 2:
return n
dp = [0, 0, 1]
for i in range(2, n + 1):
dp[0] = dp[1]
dp[1] = dp[2]
dp[2] = dp[0] + dp[1]
return dp[2]
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.