ProgrammingHardAccenture · Cognizant

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

Array a = [2,3,1,1,4,2,1,3,1,1] (0-based). From index i you may jump forward at most a[i] positions. Starting at index 0, the greedy below counts the minimum number of jumps to reach the last index. What is printed?
n = 10; 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. 5
  2. B. 9
  3. C. 1
  4. D. 4

Correct answer: D. 4

The farthest reachable index is extended in each window, and a jump is counted when the current window ends. Following only the first index of the array in each step, counting loop iterations, and updating the window before extending it each give different counts.

More Pseudocode and Code Tracing questions

Exams that ask this topic