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 13 of 100

What is the time complexity of a typical dynamic programming algorithm? Explain with an example.?

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

The time complexity of a typical dynamic programming algorithm depends on several factors such as the size of the input, the number of subproblems, and the amount of computation required for solving each subproblem.

In general, dynamic programming algorithms have a time complexity of O(n * m) where n is the size of the input and m is the number of subproblems. However, some dynamic programming problems may have a time complexity of O(n3) or even higher.

Let’s consider the classic example of the Fibonacci sequence which can be solved using dynamic programming. The Fibonacci sequence is a sequence of numbers in which each number is the sum of the two preceding ones. The first two numbers in the sequence are 0 and 1.

The naive recursive algorithm for computing the nth Fibonacci number has a time complexity of O(2n) which is very inefficient for large values of n. However, we can solve the problem using dynamic programming by computing the smaller subproblems first and then reusing their results to compute the larger subproblems.

Here’s the Java code for solving the Fibonacci sequence using dynamic programming:

public static int fib(int 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 code, we create an array of size n+1 to store the results of the subproblems. We initialize the first two elements of the array with the base cases of the problem. Then, we use a for loop to compute the ith Fibonacci number by adding the (i-1)th and (i-2)th Fibonacci numbers together.

The time complexity of this algorithm is O(n) because we need to solve n subproblems, and each subproblem takes constant time. Therefore, the dynamic programming solution is much faster than the recursive solution for large values of n.

In summary, the time complexity of a typical dynamic programming algorithm depends on the number of subproblems, the amount of computation required for solving each subproblem, and the size of the input. However, dynamic programming algorithms are often much faster than other algorithms for solving complex optimization problems.

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