Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: What is the minimum number of jumps needed to reach the last index of [1, 2, 1, 1, 1] when a[i] is the maximum jump length from i? Run the greedy code.

Problem: What is the minimum number of jumps needed to reach the last index of [1, 2, 1, 1, 1] when a[i] is the maximum jump length from i? Run the greedy code.
a = [1, 2, 1, 1, 1]
n = len(a)
jumps = cur = far = 0
for i in range(n - 1):
    far = max(far, i + a[i])
    if i == cur:
        jumps += 1
        cur = far
print(jumps)
What is printed?
  1. A. 4
  2. B. 2
  3. C. 3
  4. D. 5

Correct answer: C. 3

From index 0 the only move reaches index 1; from index 1 the farthest reach is index 3, and one more jump reaches index 4. That is 3 jumps.

More Coding Interview Problems questions

Exams that ask this topic