WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Dynamic Programming · Basic · question 7 of 100

Implement the Fibonacci sequence using dynamic programming with a bottom-up approach.?

📕 Buy this interview preparation book: 100 Dynamic Programming questions & answers — PDF + EPUB for $5

The Fibonacci sequence is a sequence of numbers in which each number after the first two is the sum of the two preceding ones. In mathematical terms, it can be defined as:

F(n) = F(n-1) + F(n-2), where F(0) = 0 and F(1) = 1.

A straightforward recursive solution to this problem looks like this:

int fibonacci(int n) {
    if (n <= 1) {
        return n;
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
}

However, this solution is inefficient for large values of n since it recomputes the same values multiple times. Dynamic programming can help us improve the efficiency of this algorithm by storing the results of previously computed values and reusing them if necessary.

Here’s the bottom-up approach to implementing the Fibonacci sequence using dynamic programming:

public static int fibonacci(int n) {
    if (n <= 1) {
        return n;
    }

    int[] memo = new int[n + 1];
    memo[0] = 0;
    memo[1] = 1;

    for (int i = 2; i <= n; i++) {
        memo[i] = memo[i - 1] + memo[i - 2];
    }

    return memo[n];
}

In this solution, we create an array called memo to store the results of previously computed Fibonacci numbers. We start by initializing memo[0] and memo[1] to their respective values in the sequence.

We then use a loop to iterate from i=2 up to n, computing and storing each new Fibonacci number in the memo array. By the time we reach the end of the loop, memo[n] will contain the desired Fibonacci number.

This approach has a time complexity of O(n) and a space complexity of O(n), which is more efficient than the recursive approach discussed earlier.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Dynamic Programming interview — then scores it.
📞 Practice Dynamic Programming — free 15 min
📕 Buy this interview preparation book: 100 Dynamic Programming questions & answers — PDF + EPUB for $5

All 100 Dynamic Programming questions · All topics