Fern's Adventure
Frequency: Reported
An array represents values on circular pads. The unique maximum value marks the starting pad.
From pad i, jump clockwise or counterclockwise by the value stored at that pad. Return the minimum number of hops required to return to the starting pad, or -1 if returning is impossible.
Reported constraints:
n < 1000;- pad values are less than 100,000; and
- the maximum value is not equal to
n.
Reported answer
python
def FernsAdventure(arr):
n = len(arr)
if n <= 1:
return -1
try:
start_idx = arr.index(max(arr))
except ValueError:
return -1
q = deque([(start_idx, 0)])
v = {start_idx}
while queue:
curr_idx, curr_hops = queue.popleft()
hop_val = arr[curr_idx]
next_cw = (curr_idx + hop_val) % n
next_ccw = (curr_idx - hop_val) % n
for next_pad in [next_cw, next_ccw]:
if next_pad == start_idx:
return curr_hops + 1
if next_pad not in visited:
v.add(next_pad)
q.append((next_pad, curr_hops + 1))
return -1As reported, the answer initializes q and v but later refers to queue and visited. Those names would need to be made consistent for the code to run.