ProgrammingVery hardTCS NQT · Accenture

Array a = [1, 1, 1, 1] (0-based). From index i you may jump forward by at most a[i] positions. The greedy below counts the minimum number of jumps needed to reach the last index starting from index 0. What is printed?

Array a = [1, 1, 1, 1] (0-based). From index i you may jump forward by at most a[i] positions. The greedy below counts the minimum number of jumps needed to reach the last index starting from index 0. What is printed?
n = 4; jumps = 0; end = 0; far = 0
for i = 0 to n - 2
    far = max(far, i + a[i])
    if i == end then jumps = jumps + 1; end = far
end for
Print jumps
  1. A. 1
  2. B. 3
  3. C. 4
  4. D. 0

Correct answer: B. 3

Each index can reach only the next one, so every step is a jump and there are 3 jumps to reach index 3. Testing i > end instead of i == end gives 1, counting the array length gives 4, and a total multiplied by zero gives 0.

More Pseudocode and Code Tracing questions

Exams that ask this topic