Jump Game II
Master this topic with zero to advance depth.
Jump Game II
You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].
Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where:
0 <= j <= nums[i]andi + j < n
Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1].
Visual Representation
Index: 0 1 2 3 4
Value: 2 3 1 1 4
Step 1: At index 0 (val 2). Can jump to 1 or 2.
Step 2: From index 1 (val 3). Can jump to 4 (Goal!).
Total Jumps: 2Examples
Jump 1 step from index 0 to 1, then 3 steps to the last index.
Level I: Dynamic Programming (Bottom-Up)
Intuition
Define dp[i] as the minimum jumps to reach the end starting from index i. To find dp[i], we 'look ahead' at all reachable indices j and pick the best one.
Thought Process
dp[i]is the min jumps from indexiton-1.- Base case:
dp[n-1] = 0. - Recurrence:
dp[i] = 1 + min(dp[j])for alli < j <= i + nums[i]. - Initialize
dpwith infinity.
Pattern: DAG Shortest Path
Detailed Dry Run
nums = [2, 3, 1, 1, 4]
| i | Range | Best Next | dp[i] |
|---|---|---|---|
| 4 | - | - | 0 |
| 3 | [4] | idx 4 (0) | 1 |
| 2 | [3] | idx 3 (1) | 2 |
| 1 | [2,3,4] | idx 4 (0) | 1 |
| 0 | [1,2] | idx 1 (1) | 2 |
Level II: Breadth-First Search (Queue-Based)
Intuition
Each jump can be seen as a 'level' in BFS. Indices reachable in 1 jump are Level 1, indices reachable in 2 jumps are Level 2, etc. Use a queue to traverse until is reached.
Thought Process
- Queue stores
(index, levels). - Use
visitedset to avoid cycles/redundancy. - For each popped index, push all unvisited neighbors .
Pattern: Level-Order Traversal
Detailed Dry Run
nums = [2, 3, 1, 1, 4] q: [(0,0)]. Pop (0,0). Push (1,1), (2,1). Vis={0,1,2}. Pop (1,1). Push (3,2), (4,2). Reach end! Return 2.
Level III: Optimal Greedy (Window-Based BFS)
Intuition
Maintain a 'window' of reachable indices for the current number of jumps. When we reach the end of the current window, we increment jump count and move to the farthest point reachable from that window.
Thought Process
jumps,curEnd,farthestvariables.- Iterate through array (excluding last index).
- Update
farthest = max(farthest, i + nums[i]). - If
i == curEnd, updatecurEnd = farthest,jumps++.
Pattern: Greedy Reachability
Detailed Dry Run
[2,3,1,1,4] i=0: f=2. i==curEnd(0). end=2, jumps=1. i=1: f=4. OK. i=2: f=4. i==curEnd(2). end=4, jumps=2. Result: 2.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.