Data Structures & AlgorithmsHardProduct Company SDE · greedy OA

Problem: Each element of [2, 3, 1, 1, 4] is the maximum jump length from that index. What is the minimum number of jumps to reach the last index? Run the greedy code.

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

Correct answer: A. 2

Jump from index 0 reaches index 1 or 2; from index 1 (reach 4) one more jump reaches the last index. The greedy keeps the farthest reach in each jump layer.

More Coding Interview Problems questions

Exams that ask this topic