55. Jump Game
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Greedy
- Time
- O(N)
- Space
- O(1)
Standard Solution (C++)
SummaryGiven an array where each element represents the maximum number of steps you can jump forward from that position, determine whether you can reach the last index starting from index 0.
Approach
- Track
maxReach, the farthest index reachable so far. - At each index
i, ifi > maxReachthe position is unreachable and we immediately returnfalse. - Otherwise, update
maxReach = max(maxReach, i + nums[i]). - If
maxReachever reaches or exceeds the last index, returntrue; if the loop ends without doing so, returnfalse. This greedy strategy works because extending the reach greedily never sacrifices future options.
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
bool canJump(vector<int>& nums) {
int maxReach = 0; // farthest index we can currently reach
int last = (int)nums.size() - 1;
for (int i = 0; i <= last; ++i) {
if (i > maxReach) return false; // current index is unreachable
maxReach = max(maxReach, i + nums[i]);
if (maxReach >= last) return true; // can already reach the end
}
return true; // last index was reachable throughout the loop
}
};
Time O(n) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
class Solution {
public:
bool canJump(vector<int>& nums) {
int curFarthest=0;
int len=nums.size();
for(int i=0; i<len; ++i){
if(curFarthest>=len-1){
return true;
}
if(curFarthest<i){
return false;
}
curFarthest=std::max(curFarthest, i+nums[i]);
}
return false;
}
};
// 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.