45. Jump Game II
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Greedy
- Time
- O(N)
- Space
- O(1)
Standard Solution (C++)
SummaryGiven an integer array where each element represents the maximum jump length from that position, find the minimum number of jumps needed to reach the last index from the first index.
Approach
- Use a greedy "implicit BFS levels" approach: treat each jump as a level, tracking the farthest reachable index within the current level.
- Maintain two pointers:
currentEnd(the boundary of the current jump's reach) andfarthest(the maximum index reachable from any position seen so far). - When the loop reaches
currentEnd, a new jump must be taken — increment the counter and advancecurrentEndtofarthest. - This works because at each boundary we greedily extend as far as possible, guaranteeing the fewest jumps to cover the array.
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size();
int jumps = 0;
int currentEnd = 0; // boundary of the current jump level
int farthest = 0; // farthest index reachable so far
// Only iterate up to n-2: once currentEnd reaches or passes n-1 we're done
for (int i = 0; i < n - 1; ++i) {
farthest = max(farthest, i + nums[i]);
// Reached the end of the current jump level — must take another jump
if (i == currentEnd) {
++jumps;
currentEnd = farthest;
if (currentEnd >= n - 1) break; // already can reach the last index
}
}
return jumps;
}
}; Time O(n) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
class Solution {
public:
int jump(vector<int>& nums) {
// use greedy algorithm
// iterate from 0 to n-1, each time we keep "the max_pos we can jump to" and "the min number of jumps"
int max_pos=0;
int end=0;
int jumps=0;
int n=nums.size();
if(n==1)
return 0;
for(int i=0; i<n-1; ++i){
max_pos=std::max(max_pos, i+nums[i]);
if(i==end){
++jumps;
end=max_pos;
if(end>=n-1)
return jumps;
}
}
return jumps;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) Time O(N) Space O(1)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.