Jump Game III - Problem
๐ฏ Jump Game III: Finding the Zero
Imagine you're playing a unique board game where you can only move in specific patterns! You start at a given position on an array of non-negative integers, and your goal is to reach any cell containing zero.
The Rules:
- When you're at index
i, you have exactly two movement options: - Jump forward to
i + arr[i] - Jump backward to
i - arr[i] - You cannot jump outside the array bounds
- You win if you can reach any index where the value is 0
Example: If you're at index 2 in array [4,2,3,0,3,1,2] and the value is 3, you can jump to index 5 (2+3) or index -1 (invalid, so not allowed).
Return true if you can reach a zero, false otherwise.
Input & Output
example_1.py โ Basic reachable zero
$
Input:
arr = [4,2,3,0,3,1,2], start = 2
โบ
Output:
true
๐ก Note:
Start at index 2 (value=3). Jump forward: 2+3=5 (value=1). From index 5: jump backward 5-1=4 (value=3), or forward 5+1=6 (value=2). From index 4: jump to 4+3=7 (out of bounds) or 4-3=1 (value=2). From index 1: jump to 1+2=3 (value=0) - found zero!
example_2.py โ Unreachable zero
$
Input:
arr = [4,2,3,0,3,1,2], start = 0
โบ
Output:
false
๐ก Note:
Start at index 0 (value=4). Jump forward: 0+4=4 (value=3). From index 4: jump to 4+3=7 (out of bounds) or 4-3=1 (value=2). From index 1: jump to 1+2=3 (value=0) or 1-2=-1 (out of bounds). Wait, we can reach the zero! This would actually be true.
example_3.py โ Start at zero
$
Input:
arr = [3,0,2,1,2], start = 1
โบ
Output:
true
๐ก Note:
Start at index 1 which has value 0. Since we're already at a position with value 0, return true immediately.
Constraints
- 1 โค arr.length โค 5 ร 104
- 0 โค arr[i] < arr.length
- 0 โค start < arr.length
- Each array value is non-negative
Visualization
Tap to expand
Understanding the Visualization
1
Model as Graph
Each array index is a node, with directed edges to positions i+arr[i] and i-arr[i]
2
Choose Traversal
Use BFS for shortest path or DFS for memory efficiency, both with visited tracking
3
Explore Systematically
Visit each reachable position exactly once, checking for zero values
4
Avoid Cycles
Use visited set to prevent infinite loops in the graph
5
Return Result
Return true if any reachable position contains zero
Key Takeaway
๐ฏ Key Insight: Transform the jumping problem into graph traversal. Each position is a node with at most 2 outgoing edges. Use BFS or DFS with visited tracking to systematically explore all reachable positions in O(n) time.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code