Fibonacci using Dynamic Programming in Java and Kotlin

Carvia Tech | August 03, 2019 | 3 min read | 103 views


Before starting Dynamic Programming, we must get familiar with recursion first.

Recursion

In recursion, we simply a complex problem by breaking it down into simpler sub-problems in a recursive manner. If a problem can be composed off sub-problems, then it could be a good candidate for recursion.

Few examples of recursive problems are:

  1. Calculation of Fibonacci number

  2. Calculating factorial of a given number

General structure of recursive solution
if (base condition) {// base condition with iterative solution
    return <some simple iterative expression>
}
else {// recursive case
     some work before call()
     recursive call()
     some work after call()
}

Solution to a recursive problem is built using solution to its sub-problems. Recursive solutions can be broadly divided into two categories:

Bottom-up recursion

Here we start with knowing how to solve the problem for the simple case, like with only 1 element for factorial and then for 2 elements. Basically we build the solution for one case off of the previous case.

Top-down recursion

We start with dividing the problem for case N into sub-problems till we achieve the solution.

Notes:
  1. Recursion is helpful in writing complex algorithms in easy to understand manner.

  2. Normally iterative solutions provide better efficiency compared to recursive one because of so much overhead involved in executing recursive steps.

Calculating Fibonacci using Recursion

For example, we would use the following code to calculate the Fibonacci series using recursion

Fibonacci - Kotlin version
fun fibonacci(n: Int): Long {
    if (n == 0) return 0
    if (n == 1) return 1
    return fibonacci(n - 1) + fibonacci(n - 2)
}
Fibonacci - Java version
public class Fibonacci {
    public int fib(int n) {
        if (n <= 1) { (1)
            return n;
        } else { (2)
            return fib(n - 1) + fib(n - 2);
        }
    }
}
1 base condition
2 recursive condition
Time Complexity

Computing the nth Fibonacci number depends on the solution of previous n-1 numbers, also each call invokes two recursive calls. This means that the Time complexity of above fibonacci program is Big O (2n) i.e. exponential. That’s because the algorithm’s growth doubles with each addition to the data set.

Exponential runtime complexity
Time complexity of an algorithm is Big O (2n) i.e. exponential when its growth doubles with each addition to the input data set. It is exactly opposite to Big O (log n) where problem size is reduced to half on each successive iteration.

Dynamic Programming

Dynamic Programming is a powerful optimization technique, where a recursive problem can be solved in O (n2) or O (n3) where a naive approach would take exponential time O (2n)

The optimization in Dynamic Programming is achieved by caching the intermediate results for the future calls.

If we run the previous fibonacci program, input of 50 will take around 1 minute on a average modern hardware.

Now, we will write the same fibonacci program using Dynamic Programming:

Fibonacci - Optimized Kotlin version using Dynamic Programming
class Fibonacci {
    private val cache: MutableMap<Int, Long> = HashMap()

    fun cal(n: Int): Long {
        if (n == 0) return 0
        if (n == 1) return 1

        return when {
            cache.containsKey(n) -> cache[n]!!
            else -> {
                cache[n] = cal(n - 1) + cal(n - 2)
                cache[n]!!
            }
        }
    }
}
Fibonacci - Optimized Java version using Dynamic Programming
public class Fibonacci {
    final int max = 10000;
    int[] fib = new int[max];

    int fibonacci(int num) {
        if (num == 0) return 0;
        if (num == 1) return 1;

        if (fib[num] != 0) {
            return fib[num];    (1)
        }
        fib[num] = fibonacci(num - 1) + fibonacci(num - 2);  (2)
        return fib[num];
    }
}
1 return the cached result, if already available.
2 cache the result of computation for future use.

You can try to run the above example on your machine, even 1000th Fibonacci number will be calculated in a fraction of millisecond.

In nutshell, Dynamic Programming is an optimized recursive technique where you cache the results for use in future calls. You can always start with a normal recursive approach first and then add the caching part later on.


Top articles in this category:
  1. ION Trading Java Interview Questions
  2. Citibank Java developer interview questions
  3. RBS Java Programming Interview Questions
  4. Java Concurrency Interview Questions and Answers
  5. Top 50 Multi-threading Java Interview Questions for Investment Bank
  6. Goldman Sachs Java Interview Questions for Senior Developer
  7. BlackRock Top Java Interview Questions: Investment Banking Domain


Find more on this topic:
Java Interviews image
Java Interviews

Interview - Product Companies, eCommerce Companies, Investment Banking, Healthcare Industry, Service Companies and Startups.

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info