ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (Arrays are indexed from 0)

What will be the output of the following pseudocode? (Arrays are indexed from 0)
Integer a[5] = {2, 3, 1, 1, 4}
Integer jumps = 0, curEnd = 0, far = 0
for (each i from 0 to 3)
    far = max(far, i + a[i])
    if (i == curEnd)
        jumps = jumps + 1
        curEnd = far
    end if
end for
Print jumps
  1. A. 3
  2. B. 4
  3. C. 1
  4. D. 2

Correct answer: D. 2

a[i] is the longest jump from index i; the greedy loop counts the fewest jumps to reach the end. From index 0 you can reach index 1 or 2; from index 1 (value 3) you reach the last index: 2 jumps.

More Pseudocode and Code Tracing questions

Exams that ask this topic