Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: From index i of an array you may jump to i + a[i] or i − a[i] (staying inside). Can you reach any index holding 0? (BFS.)

Problem: From index i of an array you may jump to i + a[i] or i − a[i] (staying inside). Can you reach any index holding 0? (BFS.)
from collections import deque
def reach_zero(a, start):
    q, seen = deque([start]), {start}
    while q:
        i = q.popleft()
        if a[i] == 0: return True
        for j in (i + a[i], i - a[i]):
            if 0 <= j < len(a) and j not in seen: seen.add(j); q.append(j)
    return False
print(reach_zero([3, 2, 0, 1, 4, 2], 4), reach_zero([3, 2, 0, 1, 4, 2], 1), reach_zero([1, 3, 1, 0], 0))
What is printed?
  1. A. True False False
  2. B. False True False
  3. C. True True True
  4. D. True True False

Correct answer: D. True True False

Indices are nodes with up to two edges each. From 4: 4 → 0 → 3 → 2 (a[2] = 0) → True. From 1: 1 → 3 → 2 → True. In [1, 3, 1, 0] from 0: 0 → 1, and from 1 both jumps (4 and −2) leave the array → False, even though a 0 exists. The seen set prevents infinite loops. O(n).

More Coding Interview Problems questions

Exams that ask this topic