45. Jump Game II - Detailed Explanation
Problem Statement
Description:
You are given an array of non-negative integers nums. Each element in the array represents your maximum jump length from that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index.
Example 1:
- Input:
nums = [2, 3, 1, 1, 4] - Output:
2 - Explanation:
- Jump 1: From index 0, jump 1 step to index 1 (or 2, but choosing index 1 is optimal here because it allows a jump to the end).
- Jump 2: From index 1, jump 3 steps to index 4 (last index).
Example 2:
- Input:
nums = [2, 1] - Output:
1 - Explanation:
- From index 0, jump directly to index 1.
Constraints:
- 1 ≤
nums.length≤ 10⁴ (or more in some variations) - 0 ≤
nums[i]≤ 1000 - It is guaranteed that you can always reach the last index.
Hints
-
Hint 1:
Think about how far you can reach from each index. As you move along the array, keep track of the farthest index you can get to. -
Hint 2:
At each step, consider the current range you can reach with the current number of jumps and determine the farthest point you can jump to in the next move. -
Hint 3:
A greedy strategy works well here: while traversing the current jump range, update the farthest reachable index. When you pass the current range, you increment the jump counter and update the range to this farthest point.
Approach 1: Greedy Algorithm (Optimal)
Idea
The optimal greedy solution works by maintaining a current range (the farthest index reachable with the current number of jumps) and a farthest (the farthest index that can be reached by using one more jump within the current range).
Steps:
-
Initialize Variables:
jumps: count of jumps taken.current_end: the end of the current jump range.farthest: the farthest index reachable within the current range.
-
Iterate Through the Array:
- For each index
iin the array (except the last index), updatefarthestasmax(farthest, i + nums[i]). - When you reach the end of the current range (
i == current_end), you have finished exploring the current jump. Incrementjumpsand updatecurrent_endtofarthest. - Continue until you reach or exceed the last index.
- For each index
-
Return the Number of Jumps:
After processing the array, thejumpsvariable holds the minimum number of jumps required.
Visual Walkthrough
For nums = [2, 3, 1, 1, 4]:
-
Initial:
jumps = 0,current_end = 0,farthest = 0.
-
Iteration:
-
i = 0:
- From index 0, you can jump up to index 0 + 2 = 2.
- Update
farthest= max(0, 2) = 2. - Since
iequalscurrent_end(0 == 0), incrementjumpsto 1 and setcurrent_end=farthest(2).
-
i = 1:
- From index 1, you can jump up to index 1 + 3 = 4.
- Update
farthest= max(2, 4) = 4.
-
i = 2:
- From index 2, you can jump up to index 2 + 1 = 3.
farthestremains max(4, 3) = 4.- Now,
iequalscurrent_end(2 == 2) from the previous range, so incrementjumpsto 2 and updatecurrent_endtofarthest(4).
-
-
At this point,
current_end(4) reaches the last index. -
Output:
2jumps are needed.
Approach 2: Dynamic Programming (Less Optimal)
Idea
The dynamic programming approach calculates the minimum jumps needed to reach each index and builds up the solution.
Steps:
-
Initialize an Array
dp:
Create an arraydpwheredp[i]represents the minimum number of jumps required to reach indexi. Initializedp[0]to 0 and the rest to a large number (or infinity). -
Update DP Array:
For every indexi, iterate through the indices reachable fromi(fromi+1tomin(i + nums[i], n-1)) and updatedp[j] = min(dp[j], dp[i] + 1). -
Result:
The answer will bedp[n-1].
Discussion
- Pros:
- It is straightforward to understand and implement.
- Cons:
- The time complexity is O(n²) in the worst case, which is less efficient than the greedy approach for larger input sizes.
Code Implementation
Python Code (Greedy Approach)
Java Code (Greedy Approach)
Complexity Analysis
- Greedy Approach:
- Time Complexity: O(n) because we traverse the array once.
- Space Complexity: O(1) extra space.
- Dynamic Programming Approach (if used):
- Time Complexity: O(n²) in the worst case due to nested loops.
- Space Complexity: O(n) for the DP array.
Step-by-Step Walkthrough and Visual Example
Using nums = [2, 3, 1, 1, 4]:
-
Initialization:
jumps = 0,current_end = 0,farthest = 0.
-
i = 0:
- Calculate farthest = max(0, 0 + 2) = 2.
i == current_end(0 == 0), so make a jump:- Increment
jumpsto 1. - Update
current_end=farthest= 2.
- Increment
-
i = 1:
- Calculate farthest = max(2, 1 + 3) = 4.
iis not equal tocurrent_endyet.
-
i = 2:
- Calculate farthest = max(4, 2 + 1) = 4.
i == current_end(2 == 2), so make another jump:- Increment
jumpsto 2. - Update
current_end=farthest= 4.
- Increment
- Since
current_end(4) is the last index, we can exit.
-
Final Result:
- Minimum number of jumps is
2.
- Minimum number of jumps is
Common Mistakes and Edge Cases
Common Mistakes
-
Forgetting to Update the Farthest Reachable Index:
Make sure you update the farthest variable inside the loop. -
Not Handling Single-Element Arrays:
Ifnumshas only one element, no jumps are needed. -
Off-by-One Errors:
Be careful when iterating ton - 1since you don’t need to jump from the last index.
Edge Cases
-
Single Element Array:
Input:[0]→ Output:0jumps. -
Arrays with All Ones:
Every jump moves only one index forward, so the number of jumps equalsn - 1.
GET YOUR FREE
Coding Questions Catalog
$197

$78
$78