3,871 views
0 0 votes

Consider the following code segment to find the $n^{th}$ Fibonacci number:

Fib(n)
{
   if(n==0) {return 0;}
 
   if(n==1) {return 1;}
   
   else { return(Fib(n-1) + Fib(n-2)); }
}


The time complexity of the above code and time complexity of the same problem solved using dynamic programming is______
$A)O(n^{2}),O(n)$
$B)O(2^{n}),O(n)$
$C)O(2^{n}),O(n^{2})$
$D)$None of the above 

2 Answers

0 0 votes

first part is easy we can solve recurrence relation t(n)=t(n-1)+t(n-2)+c=0(2$^{n}$)

for second part we can make a programm like this

public static int fibonacciLoop(int nthNumber) {
        //use loop
        int previouspreviousNumber, previousNumber = 0, currentNumber = 1;

        for (int i = 1; i < nthNumber ; i++) {

            previouspreviousNumber = previousNumber;

            previousNumber = currentNumber;

            currentNumber = previouspreviousNumber + previousNumber;

        }
        return currentNumber;
    }

time complexity=0(n).

reference=https://dev.to/khalilsaboor/fibonacci-recursion-vs-iteration--474l

0 0 votes
option B) is correct answer,  Without DP – O(2^n) , using masters theorem

Using DP – every time time result is calculated store it in an array, if result is already computed then there is no need to compute it again. Therefore in worst case complexity is O(n) ie size of the array.
Position:
Show:

Related questions

1 1 vote
1 1 answer
7.5k
7.5k views
Tuhin Dutta asked Dec 13, 2017
7,477 views
Unlike greedy algorithms, dynamic programming method always provide correct/optimal solution.Is the above statement correct?
3 3 votes
2 answers 2 answers
974
974 views
Bikram asked May 26, 2017
974 views
Match the following:$\begin{array}{|l|l|l|l|} \hline (1) & \text{Multistage graph} & (P) & \text{Divide and conquer}\\ \hline (2) & \text{Convex hull } & (Q) & \text{Dept...
0 0 votes
1 1 answer
143
143 views
Shubham Sharma 2 asked Apr 19
143 views
Match the LIST-I with LIST-IILIST-ILIST-IIA.Dynamic programmingI.Floyd Warshall Shortest pathB.GreedyII.Huffman codingC.Back trackingIII.Hamiltonian cycle problemD.Branch...
3 3 votes
3 3 answers
7.0k
7.0k views
Arjun asked Jul 2, 2019
6,982 views
Consider the following steps:$S_1$: Characterize the structure of an optimal solution$S_2$: Compute the value of an optimal solution in bottom-up fashionWhich of the foll...