Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: From index 0, a[i] is the longest jump allowed from i. Find the minimum number of jumps to reach the last index (greedy BFS by levels).
Problem: From index 0, a[i] is the longest jump allowed from i. Find the minimum number of jumps to reach the last index (greedy BFS by levels).
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([3, 1, 2, 1, 1, 4, 1, 1, 2]))What is printed?- A. 4
- B. 3
- C. 5
- D. 6
Correct answer: A. 4
Level 1 reaches index 3; from indices 1–3 the farthest is 4; from 4 only 5; from 5 the jump of 4 reaches index 9 ≥ 8. That is 4 jumps (0→2→4→5→end). Looking ahead greedily from 0 to the biggest value does not save a jump because index 4 is a bottleneck.
More Coding Interview Problems questions
- Problem: Split a string into as many parts as possible so that each letter appears in at most one part; return the part sizes. python def…
- How many structurally different binary search trees can be built on the keys 1..7 if the ROOT must be 3?
- Problem: Count the ways to tile a 2 × n board with 2 × 1 dominoes and L-shaped trominoes (both rotatable). python def tilings(n): dp = [1…
- What is the time complexity of this loop? python i = n while i > 0: for j in range(i): work() # O(1) i //= 2
- Recursive quicksort can need O(n) stack depth on adversarial input. Which change GUARANTEES O(log n) extra stack space even in the worst…
- Problem: Find the shortest substring of s that contains every character of t, counting duplicates (return the leftmost one on ties)…