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?- A. 4
- B. -1
- C. 3
- 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
- Trapping rain water: heights h = [4, 2, 0, 3, 2, 5, 1, 0, 2]. Compute the total water trapped between the bars. python…
- The permutation p = [4, 3, 1, 7, 6, 2, 5] of 1..7 must be sorted by swaps of any two elements. What is the minimum number of swaps?…
- Count the lattice paths of length 8 with steps +1 and −1 that start at 0, never go below 0, and end at 0. Run the DP over positions and…
- How many ways are there to tile a 3 × 8 board completely with 1 × 2 dominoes (placed horizontally or vertically)? Count by DFS over the…
- Meetings are given as half-open intervals [(0,30),(5,10),(15,20),(12,25),(28,35)]. What is the minimum number of meeting rooms needed so…
- Count the unordered pairs (i < j) of the array a = [1, 2, ..., 14] whose sum is divisible by 3. Run the code. python a=list(range(1,15))…