GATE / CS ARCHIVE

GATE CSE 2000 / QUESTION 16(a)

Memoize Fibonacci recursion

Algorithms · Dynamic Programming · Full GATE CSE 2000 paper

GATE 2000, Q16(a) Descriptive
Report issue

Dynamic Programming

Question 16(a), 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. Fill the three boxes.
Question 16(a), 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. Fill the three boxes.
Tap to enlarge
Answer & solution

Answer: (1) f[n]!=0; (2) f[n]; (3) f[n]=t; (no official key was published)

The completed function is:
fib(n) {
  if (n > M) error();
  if (n == 0) return 1;
  if (n == 1) return 1;
  if (f[n] != 0) return f[n];
  t = fib(n-1) + fib(n-2);
  f[n] = t;
  return t;
}

Use a local t in each recursive activation. Since both base cases equal 1, every valid Fibonacci result is positive. Thus zero safely means “not computed” under the stated exact-arithmetic model. On a cache miss, recursively obtain the two predecessors, store their sum before returning, and reuse it whenever n is requested again. For example fib(4) obtains fib(3)=3, then reads the cached fib(2)=2, producing 5. The base cases need not be stored because they already take constant time. With overflowing machine arithmetic, zero might cease to be a valid sentinel; practical implementations can use an independent computed flag or arbitrary-precision values.

Original paper, page 9