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?- A. True False
- B. False False
- C. True True
- 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
- Problem: Count non-empty subsequences whose minimum + maximum ≤ target (sort, then two pointers with powers of 2). python def count(a, t)…
- Problem: Rotate an array right by k in O(1) extra space with three reversals. python def rotate(a, k): n = len(a); k %= n def rev(i, j)…
- Problem: Count primes in [L, R] with a segmented sieve (mark multiples of small primes up to √R inside the segment). python import math…
- Edge case: itertools.groupby on unsorted data. python from itertools import groupby data = "aabbbaacc" print([(k, len(list(g))) for k, g…
- Problem: Row n of Pascal's triangle built in place, plus two checks. python def row(n): r = [1] for in range(n): r = [1] + [r[i] + r[i+1]…
- Problem: Find the maximum sum of a sub-rectangle whose sum does not exceed k (fix two columns, then 'max subarray sum ≤ k' with a sorted…