Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Starting at index s, you may jump from i to i + a[i] or i − a[i]. Can you reach any index holding 0?

Problem: Starting at index s, you may jump from i to i + a[i] or i − a[i]. Can you reach any index holding 0?
def can_reach(a, s):
    seen, st = set(), [s]
    while st:
        i = st.pop()
        if a[i] == 0: return True
        seen.add(i)
        for j in (i + a[i], i - a[i]):
            if 0 <= j < len(a) and j not in seen: st.append(j)
    return False
print(can_reach([3, 4, 2, 3, 0, 3, 1, 2], 2), can_reach([2, 3, 1, 1, 0], 2))
What is printed?
  1. A. True False
  2. B. False False
  3. C. True True
  4. D. False True

Correct answer: C. True True

First array from index 2: 2 → 4 (value 0) immediately: True. Second: from index 2 (value 1) step to index 3, whose value 1 reaches index 4 (value 0), so it is True as well. The visited set stops the search from cycling.

More Coding Interview Problems questions

Exams that ask this topic