Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: From index 0, a[i] is the longest jump allowed from i. Find the minimum number of jumps to reach the last index (greedy BFS by levels).

Problem: From index 0, a[i] is the longest jump allowed from i. Find the minimum number of jumps to reach the last index (greedy BFS by levels).
def jumps(a):
    j = end = far = 0
    for i in range(len(a) - 1):
        far = max(far, i + a[i])
        if i == end:
            j += 1; end = far
    return j
print(jumps([3, 1, 2, 1, 1, 4, 1, 1, 2]))
What is printed?
  1. A. 4
  2. B. 3
  3. C. 5
  4. D. 6

Correct answer: A. 4

Level 1 reaches index 3; from indices 1–3 the farthest is 4; from 4 only 5; from 5 the jump of 4 reaches index 9 ≥ 8. That is 4 jumps (0→2→4→5→end). Looking ahead greedily from 0 to the biggest value does not save a jump because index 4 is a bottleneck.

More Coding Interview Problems questions

Exams that ask this topic