ProgrammingVery hardProduct company OA

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

What will be the output of the following pseudocode? (calls counts every call, including the first; memo starts with every entry equal to −1.)
Integer calls = 0, memo[0..20]
Function f(Integer n)
    calls = calls + 1
    if (n < 3)
        return 1
    end if
    if (memo[n] != -1)
        return memo[n]
    end if
    memo[n] = f(n - 1) + f(n - 3)
    return memo[n]
End Function
Print f(10), calls
  1. A. 28 15
  2. B. 28 17
  3. C. 19 17
  4. D. 28 9

Correct answer: B. 28 17

Values: f(0..2) = 1, f(3) = 2, f(4) = 3, f(5) = 4, f(6) = 6, f(7) = 9, f(8) = 13, f(9) = 19, f(10) = 19 + 9 = 28. Calls: the chain f(10), f(9), …, f(3), f(2) is 9 calls; each of the 8 computed values f(10)…f(3) also makes one f(n − 3) call (f(7) … f(0)), which is answered by the memo or the base case: 9 + 8 = 17. Forgetting that memo hits still count as calls gives a smaller number; 19 is f(9).

More Pseudocode and Code Tracing questions

Exams that ask this topic