Data Structures & AlgorithmsVery hardProduct Company SDE · ICPC regional

Array a = [2, 3, 1, 1, 4, 2, 0, 3, 1, 1]; from index i you may jump to any index in [i+1, i+a[i]]. Find the minimum number of jumps from index 0 to the last index.

Array a = [2, 3, 1, 1, 4, 2, 0, 3, 1, 1]; from index i you may jump to any index in [i+1, i+a[i]]. Find the minimum number of jumps from index 0 to the last index.
a=[2,3,1,1,4,2,0,3,1,1]
n=len(a); dist=[-1]*n; dist[0]=0; q=[0]
for u in q:
    for v in range(u+1,min(n,u+a[u]+1)):
        if dist[v]<0: dist[v]=dist[u]+1; q.append(v)
print(dist[n-1])
What is printed?
  1. A. 4
  2. B. -1
  3. C. 3
  4. D. 5

Correct answer: A. 4

BFS levels over the jump graph give the minimum number of jumps. Excluding the farthest reachable index drops a real jump, assuming every jump is the maximum length gives a loose bound, and always jumping by the full value is a greedy that overshoots and misreads the target.

More Coding Interview Problems questions

Exams that ask this topic