Jump Game III Problem
Description
LeetCode Problem 1306.
Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach any index with value 0.
Notice that you can not jump outside of the array at any time.
Example 1:
Input: arr = [4,2,3,0,3,1,2], start = 5
Output: true
Explanation:
All possible ways to reach at index 3 with value 0 are:
index 5 -> index 4 -> index 1 -> index 3
index 5 -> index 6 -> index 4 -> index 1 -> index 3
Example 2:
Input: arr = [4,2,3,0,3,1,2], start = 0
Output: true
Explanation:
One possible way to reach at index 3 with value 0 is:
index 0 -> index 4 -> index 1 -> index 3
Example 3:
Input: arr = [3,0,2,1,2], start = 2
Output: false
Explanation: There is no way to reach at index 1 with value 0.
Constraints:
1 <= arr.length <= 5 * 10^40 <= arr[i] < arr.length0 <= start < arr.length
Solution
Approach: Graph Search
Think of each index as a node with at most two edges: to i + arr[i] and to i - arr[i], when they are inside the array. The question is whether some index with value 0 can be reached from start, which is a plain graph search.
Keep a stack of indices to visit, starting with start. Pop an index; if its value is 0 we are done. Otherwise push the two jump targets that are inside the array and not seen yet. If the stack runs empty, no zero is reachable.
The seen array matters: jumps can go back and forth (in Example 3, index 2 jumps to 0 and 4, and 4 jumps back to 2), so without it the search would loop forever. Marking an index when it is pushed means each index enters the stack at most once.
We use an explicit stack instead of recursion because a path can visit all 5 * 104 indices, which is too deep for the default call stack in some languages.
Complexity: O(n) time and O(n) space, since every index is pushed at most once.
class Solution:
def canReach(self, arr: List[int], start: int) -> bool:
n = len(arr)
seen = [False] * n
seen[start] = True
stack = [start]
while stack:
i = stack.pop()
if arr[i] == 0:
return True
for j in (i + arr[i], i - arr[i]):
if 0 <= j < n and not seen[j]:
seen[j] = True # mark on push, so each index is visited once
stack.append(j)
return False