Jump Game III

Given an array of non-negative integers arr, you are initially positioned at index start. 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.

30:00

Jump Game III
medium
Free written solution
Topics
Companies

Given an array of non-negative integers arr, you are initially positioned at index start. 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
Constraints:
  • 1≤arr.length≤5×1041 \leq \text{arr.length} \leq 5 \times 10^4

  • 0≤arr[i]<arr.length0 \leq \text{arr}[i] < \text{arr.length}

  • 0≤start<arr.length0 \leq \text{start} < \text{arr.length}

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"arr":[4,2,3,0,3,1,2],"start":5}

Stand on index 5. Each index i is a node with two edges: to i + arr[i] and i - arr[i]. BFS from 5 and stop at the first index holding 0.

402132033415#126

→ new index, enqueue

⇢ already visited

⇢ off the array

■ value 0 (target)

queue (1)

5

visited

1 / 7

Variables
VariableValue
n7
start5
i-
queue1
DepthFunction Call
Stack empty
0/11