Dynamic Programming
![Question 16(b), GATE 2000: Array f[0..M] starts at zero. fib(n) checks n>M for error, returns 1 for n=0 or 1, then executes if([1]) return [2]; t=fib(n−1)+fib(n−2); [3]; return t. Assume 0<=n<=M and exact arithmetic. With memoization filled correctly, find the running time of the first fib(n) computation.](../../assets/questions/CS-2000-Q81-1.webp)
![Question 16(b), GATE 2000: Array f[0..M] starts at zero. fib(n) checks n>M for error, returns 1 for n=0 or 1, then executes if([1]) return [2]; t=fib(n−1)+fib(n−2); [3]; return t. Assume 0<=n<=M and exact arithmetic. With memoization filled correctly, find the running time of the first fib(n) computation.](../../assets/questions/CS-2000-Q81-2.webp)
![Question 16(b), GATE 2000: Array f[0..M] starts at zero. fib(n) checks n>M for error, returns 1 for n=0 or 1, then executes if([1]) return [2]; t=fib(n−1)+fib(n−2); [3]; return t. Assume 0<=n<=M and exact arithmetic. With memoization filled correctly, find the running time of the first fib(n) computation.](../../assets/questions/CS-2000-Q81-3.webp)
Answer & solution
Answer: Θ(n) time in the unit-cost arithmetic model; Θ(n) recursion depth and used cache cells. (no official key was published)
For each k from 2 through n there is at most one cache miss. That miss performs a constant number of comparisons, two recursive calls, one addition and one store. All later calls on the same k return from the cache in constant time. The subproblem dependency graph has n+1 possible arguments and two outgoing calls per non-base argument, so the total number of calls and primitive operations is O(n), not exponential. A first computation must actually compute each of fib(2),...,fib(n), giving Ω(n) work; therefore the tight bound is Θ(n). The descent n,n−1,...,1 can occupy Θ(n) stack frames. Initializing the provided whole array costs Θ(M) separately, but the stem says it is already initialized. If bit complexity is counted, Fibonacci numbers have Θ(n) bits, and the n additions have increasing cost; the conventional linear answer assumes constant-time arithmetic.