Jump Game - I
Problem Statement:β
You are given an integer arrayΒ nums. You are initially positioned at the array'sΒ first index, and each element in the array represents your maximum jump length at that position.
ReturnΒ trueΒ if you can reach the last index, orΒ falseΒ otherwise.
-
Example:
Example 1:
Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
β Solution: Greedyβ
class Solution {
public:
bool canJump(vector<int>& nums) {
int furthestReachable = 0;
for(int currentIndex = 0; currentIndex < nums.size(); currentIndex++) {
// If current index is not reachable
if(currentIndex > furthestReachable){
return false;
}
// Update the furthest index we can reach from here
furthestReachable = max(furthestReachable, currentIndex + nums[currentIndex]);
}
return true;
}
};
π Revision Notesβ
π How It Worksβ
- Youβre given an array where each element tells you maximum jump length from that position.
- Start from index
0and track the furthest index you can reach (furthestReachable). - If you reach an index greater than
furthestReachable, it means you canβt proceed β returnfalse. - If the loop completes, it means the last index is reachable β return
true.
π§© Key Formula / Transitionβ
-
Maintain:
furthestReachable = max(furthestReachable, currentIndex + nums[currentIndex]) -
If
currentIndex > furthestReachable, returnfalse.
β±οΈ Time & Space Complexityβ
| Metric | Value |
|---|---|
| Time | O(N) |
| Space | O(1) |
β οΈ Edge Casesβ
nums = [0]β Already at the end, returntrue.nums = [0,1,2]β Canβt move from index 0, returnfalse.- Large jumps early on cover entire array.
π‘ Other Approachesβ
| Approach | Time | Space | Status |
|---|---|---|---|
| DP (Top-down) | O(NΒ²) | O(N) | β TLE |
| Greedy | O(N) | O(1) | β Optimal |
π Related Problemsβ
π¬