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 cannot jump outside of the array at any time.

Input & Output

Example 1 — Basic Reachable Case
$ Input: arr = [4,2,3,0,3,1,2], start = 5
Output: true
💡 Note: Start at index 5 (value 1). Can jump to index 6 (5+1) or index 4 (5-1). From index 4 (value 3), can jump to index 1 (4-3) or index 7 (out of bounds). From index 1, can reach index 3 which has value 0.
Example 2 — Unreachable Zero
$ Input: arr = [4,2,3,0,3,1,2], start = 0
Output: true
💡 Note: Start at index 0 (value 4). Can jump to index 4 (0+4). From index 4 (value 3), can reach index 1 or 7. From index 1, can reach index 3 which has value 0.
Example 3 — No Zero Reachable
$ Input: arr = [3,0,2,1,2], start = 2
Output: false
💡 Note: Start at index 2 (value 2). Can jump to index 0 (2-2) or index 4 (2+2). From these positions, cannot reach index 1 which contains the only zero.

Constraints

  • 1 ≤ arr.length ≤ 5 × 104
  • 0 ≤ arr[i] < arr.length
  • 0 ≤ start < arr.length

Visualization

Tap to expand
Jump Game III - DFS Solution INPUT Array with jump values: 0 1 2 3 4 5 6 4 2 3 0 3 1 2 Start (index 5) Target (value 0) Jump Graph: 0 1 2 3 4 5 6 arr=[4,2,3,0,3,1,2], start=5 ALGORITHM STEPS 1 Start at index 5 arr[5]=1, can jump to 4 or 6 2 DFS to index 4 arr[4]=3, can jump to 1 or 7 3 DFS to index 1 arr[1]=2, can jump to 3 or -1 4 Reach index 3! arr[3]=0, found target! DFS Path: 5 --> 4 --> 1 --> 3 Visited: {5, 4, 1, 3} FINAL RESULT OK Found! Reached index 3 (value 0) true Starting from index 5, we can reach index 3 which has value 0. Jump Sequence: 5 --> 4 --> 1 --> 3 Key Insight: DFS explores all reachable indices by jumping left (i-arr[i]) or right (i+arr[i]). A visited set prevents infinite loops when indices can be reached multiple ways. Time: O(n), Space: O(n) - each index visited at most once. TutorialsPoint - Jump Game III | Depth-First Search with Visited Set
Asked in
Facebook 25 Amazon 18 Google 15 Microsoft 12
76.4K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen