You are given an array arr of non-negative integers of length n and a starting index start. From index i you may jump exactly arr[i] steps forward or backward, and jumps wrap around the ends of the array: from i you can move to (i + arr[i]) % n or (i - arr[i]) % n.
You cannot visit the same index more than once. Return True if you can reach any index whose value is 0, and False otherwise.
Function Signature
def can_reach_zero(arr: list[int], start: int) -> bool:
Rules
-
Indices are 0-based.
-
%
is the non-negative remainder, so every jump lands on an index from
0
to
n - 1
. For example, with
n = 7
, a backward jump of 2 from index 1 lands on
(1 - 2) % 7 = 6
. This matches Python's
%
with a positive divisor.
-
The start index counts as reached. If
arr[start] == 0
, the answer is
True
with no jumps.
-
Visiting each index at most once does not change which indices are reachable, because a path that repeats an index can be shortened by cutting out the loop.
Constraints
-
1 <= len(arr) <= 5 * 10^4
-
0 <= arr[i] < len(arr)
-
0 <= start < len(arr)
Examples
Input: arr = [4, 2, 3, 0, 3, 1, 2], start = 5
Output: True
One path is 5 to 4 (5 - 1 = 4), then 4 to 1 (4 - 3 = 1), then 1 to 3 (1 + 2 = 3), and arr[3] = 0. This path needs no wrap-around.
Input: arr = [0, 3, 1, 2], start = 2
Output: True
From index 2 (value 1) jump back to index 1. From index 1 (value 3) the forward jump wraps: (1 + 3) % 4 = 0, and arr[0] = 0. Without wrap-around the answer would be False, since the only jump from index 1 or 3 that stays inside the array is the one from 3 back to 1.
Input: arr = [2, 0, 2, 1], start = 0
Output: False
From index 0 (value 2) both jumps land on index 2, because (0 + 2) % 4 = 2 and (0 - 2) % 4 = 2. From index 2 (value 2) both jumps land back on index 0. Only indices 0 and 2 are reachable, so the zero at index 1 is never reached.