Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

509. 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).

Recursive Solution

Code

class Solution {
public:
    int fib(int n)
    {
        if (n <= 1) return n;
        return fib(n - 1) + fib(n - 2);
    }
};

Memoization(Top-Down) Method

code

class Solution {
private:
    int fibHelper(int n, vector<int>& dp)
    {
        if (n <= 1) return n;
        if (dp[n] != -1) return dp[n]; // Return the Value, if already calculated
        return dp[n] = fibHelper(n - 1, dp) + fibHelper(n - 2, dp); // Calculate and store the value
    }

public:
    int fib(int n)
    {
        vector<int> dp(n + 1, -1);
        return fibHelper(n, dp);
    }
};

Tabulation(Bottom-Up) Method

Code

class Solution {
public:
    int fib(int n)
    {
        if(n<=1) return n; // Base condition require, if n=0 the dp[1] will give error
        vector<int> dp(n + 1, -1);
        dp[0] = 0;
        dp[1] = 1;
        for (int i = 2; i <= n; i++) {
            dp[i] = dp[i - 1] + dp[i - 2];
        }
        return dp[n];
    }
};

Space Optimized DP Solution

Code

class Solution {
public:
    int fib(int n)
    {
        if (n <= 1) return n;
        int prev2 = 0, prev = 1;
        for (int i = 2; i <= n; i++) {
            int curr = prev + prev2;
            prev2 = prev;
            prev = curr;
        }
        return prev;
    }
};