Algo-Sim › Greedy
Jump Game II
Medium · Greedy · step through it in Java, Python and C++ on your own input
The last index is always reachable; find the fewest jumps. Scan window by window like BFS levels, jumping when the window runs out.
Problem
As in Jump Game, nums[i] is the longest jump from index i, and you start at index 0. The last index is guaranteed to be reachable. Return the minimum number of jumps needed to get there.
Constraints
- 1 ≤ nums.length ≤ 10⁴
- 0 ≤ nums[i] ≤ 1000
- The last index is always reachable
Edge cases to test
- One element:
0jumps - The first jump reaches the end
- Every value 1:
n − 1jumps
Follow-up questions
- Why is this BFS without a queue?
- Indices reachable in k jumps form a contiguous window, so the next window is just [end + 1, farthest]: O(n) time, O(1) space.
- What if some cells are unreachable?
- If a window ends with farthest ≤ the current index, return −1.
Solution
Java
public int jump(int[] nums) {
int jumps = 0, end = 0, farthest = 0;
for (int i = 0; i < nums.length - 1; i++) {
farthest = Math.max(farthest, i + nums[i]);
if (i == end) {
jumps++;
end = farthest;
}
}
return jumps;
}Python
def jump(nums):
jumps = end = farthest = 0
for i in range(len(nums) - 1):
farthest = max(farthest, i + nums[i])
if i == end:
jumps += 1
end = farthest
return jumpsC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int jump(vector<int> &nums) {
int jumps = 0, end = 0, farthest = 0;
for (int i = 0; i < int(nums.size()) - 1; i++) {
farthest = std::max(farthest, i + nums[i]);
if (i == end) {
jumps++;
end = farthest;
}
}
return jumps;
}
};
More Greedy problems
- Maximum Subarray (Medium)
- Best Time to Buy and Sell Stock II (Medium)
- Jump Game (Medium)
- Gas Station (Medium)
- Partition Labels (Medium)
- Task Scheduler (Medium)
- Hand of Straights (Medium)
- Merge Triplets to Form Target Triplet (Medium)
- Valid Parenthesis String (Medium)
- Minimum Number of Arrows to Burst Balloons (Medium)
- Candy (Hard)
- Boats to Save People (Medium)
- Two City Scheduling (Medium)