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?- A. 2 2 0
- B. 3 2 0
- C. 2 3 0
- 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
- Problem: Can you reach the last index if a[i] is the maximum jump from i? java static boolean canReach(int[] a) { int far = 0; for (int i…
- Problem: Coins of denominations {1, 7, 10} are available in unlimited supply. Pay 14 with the fewest coins. What does the greedy 'largest…
- Problem: Split a string into as many parts as possible so each letter appears in at most one part; return the part sizes. python def…
- Problem: Jobs have deadlines and profits; each takes one unit of time. Schedule to maximise profit (greedy by profit, latest free slot)…
- Problem: Given n ≤ 10⁵ intervals, find the minimum number of points such that every interval contains at least one point. Which greedy…
- Problem: Given n balloons as horizontal intervals, find the minimum number of vertical arrows that burst all of them (a balloon bursts if…