Fibonacci Series using Dynamic Programming in Java

Fibonacci Using Dynamic Programming in Java

This Fibonacci Series using Dynamic Programming article explains various methods to calculate Fibonacci numbers, from naive recursive approaches to efficient dynamic programming techniques. You will learn about the underlying principles, complete Java implementations, time and space complexity analysis, and real world use cases.

What is the Fibonacci Sequence in Java ?

What is the Fibonacci Sequence in Java ?​

Fibonacci sequence is a series of numbers where each number is the sum of the two preceding numbers.

Sequence typically begins with 0 and 1, and it is defined as follows:

F(0) = 0
F(1) = 1
F(n) = F(n – 1) + F(n – 2), for n ≥ 2

The first few Fibonacci numbers are:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

This sequence appears in various natural phenomena and mathematical structures, and it has applications in computer algorithms, biology, financial models, and more.

Recursive Approach for Fibonacci Series in Java

Recursive Approach for Fibonacci Series in Java

Simplest way to compute Fibonacci numbers is through a recursive function that directly implements the definition. However, this method has significant performance issues due to repeated computations of the same values.

Note: This method quickly becomes inefficient for large values of n because it recalculates the same values multiple times.

Run
public class FibonacciRecursive {
    static int fib(int n) {
        if (n <= 1) return n;
        return fib(n - 1) + fib(n - 2);
    }

    public static void main(String[] args) {
        int n = 10;
        System.out.println("Fibonacci of " + n + " is: " + fib(n));
    }
}
Output:
Fibonacci of 10 is 55

Now Implementing Dynamic Programming….

Dynamic programming is a method for solving complex problems by breaking them down into simpler overlapping subproblems.

It solves each subproblem once and stores the result for future use, which improves performance significantly.

Fibonacci problem is ideal for dynamic programming because it exhibits both overlapping subproblems and optimal substructure.

fibonacci series using java
fibonacci series using java

Learn DSA

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Fibonacci Series using Dynamic Programming in Java

Fibonacci Series using Dynamic Programming in Java

There are three main dynamic programming approaches for solving the Fibonacci problem:

  1. Memoization (Top Down)
  2. Tabulation (Bottom Up)
  3. Space Optimization

Method 1: Memoization (Top Down Approach)

In the memoization approach, we use recursion with caching. Results of computed Fibonacci numbers are stored in an array to avoid redundant calculations.

Memoization is more intuitive for developers who prefer recursive problem solving. However, it still uses extra memory for the recursion stack.

Run

import java.util.Arrays;

public class FibonacciMemoization {
    static int[] dp;

    static int fib(int n) {
        if (n <= 1) return n;

        if (dp[n] != -1) return dp[n];

        dp[n] = fib(n - 1) + fib(n - 2);
        return dp[n];
    }

    public static void main(String[] args) {
        int n = 10;
        dp = new int[n + 1];
        Arrays.fill(dp, -1);
        System.out.println("Fibonacci of " + n + " is: " + fib(n));
    }
}


Output:

Fibonacci of 10 is 55

Method 2: Tabulation (Bottom Up Approach)

The tabulation method uses iteration instead of recursion. It starts solving the problem from the base case and works up to the required solution.

This approach is often more efficient in terms of performance as it avoids recursion and makes the logic more deterministic.

Run
public class FibonacciTabulation {
    static int fib(int n) {
        if (n <= 1) return n;

        int[] dp = new int[n + 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];
    }

    public static void main(String[] args) {
        int n = 10;
        System.out.println("Fibonacci of " + n + " is: " + fib(n));
    }
}
Output:
Fibonacci of 10 is 55

Method 3: Space Optimized Tabulation

The tabulation method can be further optimized to use only constant space. Since each new Fibonacci number only depends on the previous two, we do not need to store the entire array.

This is the most efficient solution when only the nth Fibonacci number is required.

Run
public class FibonacciOptimized {
    static int fib(int n) {
        if (n <= 1) return n;

        int prev2 = 0, prev1 = 1;
        for (int i = 2; i <= n; i++) {
            int curr = prev1 + prev2;
            prev2 = prev1;
            prev1 = curr;
        }
        return prev1;
    }

    public static void main(String[] args) {
        int n = 10;
        System.out.println("Fibonacci of " + n + " is: " + fib(n));
    }
}
Output:
Fibonacci of 10 is 55

Advanced Method for Fibonacci Series using Dynamic Programming

Method 4: Matrix Exponentiation (Advanced)

For very large values of n, such as n > 10^6, even linear-time algorithms become slow. In such cases, matrix exponentiation can be used to compute Fibonacci numbers in logarithmic time.

The relation is based on matrix multiplication:

| F(n)   | = |1 1|^(n-1) * |1|
| F(n-1) |   |1 0|         |0|

Using fast exponentiation, we can compute powers of the matrix in O(log n) time.

This method is more complex and generally not required in basic interviews.

Comparison of Solutions for Fabonacci Series

ApproachTime ComplexitySpace ComplexityDescription
Naive RecursionO(2n)O(n)Simple but highly inefficient
Memoization (Top Down)O(n)O(n)Recursive with caching
Tabulation (Bottom Up)O(n)O(n)Iterative and efficient
Space Optimized TabulationO(n)O(1)Most efficient for single Fibonacci number
Matrix ExponentiationO(log n)O(1)Best for very large values of n

Real World Applications of Fibonacci Numbers

  1. Algorithm Design: Used as a foundation for recursive and dynamic programming algorithms.
  2. Financial Models: Used in certain trading algorithms to predict market behavior.
  3. Biology and Nature: Fibonacci numbers appear in flower petals, pine cones, and branching patterns.
  4. Data Structure Problems: Variants are used in problems such as climbing stairs, tiling, and decoding messages.
  5. Technical Interviews: Common introductory question to assess problem solving and optimization skills.

Example Problem:

Climbing Stairs Problem: You can take either 1 or 2 steps to climb a staircase. How many distinct ways are there to reach the top if there are n steps?

This is a direct application of Fibonacci numbers:

ways(n) = ways(n - 1) + ways(n - 2)

Conclusion

Fibonacci sequence is more than just a mathematical curiosity. It is a powerful tool for learning and applying dynamic programming techniques.

  • Starting from a simple recursive approach, we have explored optimized solutions using memoization, tabulation, and constant space techniques.
  • Understanding how to optimize Fibonacci calculations is a key step toward mastering dynamic programming and solving more complex algorithmic problems.

Whether you’re preparing for coding interviews or strengthening your algorithmic thinking, mastering Fibonacci using dynamic programming is essential.

FAQ's related to Fabonacci Series using Dynamic Programming

Answer:

Dynamic programming avoids redundant recursive calls by storing previously computed results. This reduces time complexity from exponential to linear.

Answer:

The space optimized tabulation method is the most efficient for moderate values of n. For extremely large values, matrix exponentiation is preferred.

Answer:

Highest Fibonacci number ever calculated is F(10 million), which has over 2 million digits. It was computed using advanced algorithms like fast doubling and matrix exponentiation with high performance computers.

Answer:

Base cases are:

F(0) = 0
F(1) = 1, these serve as the foundation for all other Fibonacci computations.

Answer:

Fibonacci series is a sequence where each number is the sum of the two previous numbers.

Series: 0, 1, 1, 2, 3, 5, 8, 13, …

Formula: F(n)=F(n−1)+F(n−2)

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription