Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Each position holds the maximum jump length from it. Return the minimum jumps to reach the last index.

Problem: Each position holds the maximum jump length from it. Return the minimum jumps to reach the last index.
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([2, 3, 1, 1, 4]), jumps([2, 3, 0, 1, 4]), jumps([0]))
What is printed?
  1. A. 2 2 0
  2. B. 3 2 0
  3. C. 2 3 0
  4. D. 2 2 1

Correct answer: A. 2 2 0

Greedy BFS by layers: everything reachable with j jumps lies up to 'end'; when i reaches end, take another jump to the farthest point seen. Both arrays need 2 (index 0 → 1 → 4). The loop stops before the last index, so [0] needs 0 jumps. O(n).

More Coding Interview Problems questions

Exams that ask this topic