ProgrammingVery hardProduct company OA · code-tracing level

What will be the output of the following pseudocode? (memo starts with every entry equal to −1; calls counts every call, including the first.)

What will be the output of the following pseudocode? (memo starts with every entry equal to −1; calls counts every call, including the first.)
Integer memo[0..20] = all -1, calls = 0
Function f(Integer n)
    calls = calls + 1
    if (n <= 1)
        return n
    end if
    if (memo[n] != -1)
        return memo[n]
    end if
    memo[n] = f(n - 1) + f(n - 2)
    return memo[n]
End Function

Print f(15), calls
  1. A. 610 29
  2. B. 610 1973
  3. C. 610 15
  4. D. 987 29

Correct answer: A. 610 29

f(15) is the 15th Fibonacci number, 610. Because f(n − 1) is evaluated first, the calls go straight down the chain f(15), f(14), …, f(2), each doing real work exactly once (14 calls). Each of these makes 2 calls; by the time f(n − 2) is called it is either memoised or a base case and returns immediately. Total calls = 1 + 2 × 14 = 29. 1973 = 2 × 987 − 1 is the call count without memoisation; 15 forgets the memo-hit calls, which still count.

More Pseudocode and Code Tracing questions

Exams that ask this topic