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?- A. True False False
- B. False True False
- C. True True True
- 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
- Problem: Paint-bucket fill: recolour the 4-connected region of the start cell's colour and report how many cells changed. python def…
- Problem: Rearrange a string so no two adjacent letters are equal ("" if impossible). Greedy: always place the most frequent remaining…
- Problem: A 'closed island' is a group of 0-cells (land) connected 4-directionally that does NOT touch the grid border. Count them. python…
- Problem: On a board of 'X' and 'O', capture every 'O' region not connected to the border by turning it into 'X'. Mark border-connected…
- Problem: Run Bellman–Ford from node 0 on a directed graph with negative edges, then check for a negative cycle with one more relaxation…
- Problem: All-pairs shortest paths with Floyd–Warshall on a 4-node directed graph (INF = no path). python INF = float("inf") def floyd(n…