Jump Game I
Can you reach the last index? Track the maximum reachable index in one greedy pass.
2 min read
greedy array
Problem#
nums[i] is your max jump length from index i. Return true iff you can reach the last index starting from index 0.
Examples#
[2,3,1,1,4]→true[3,2,1,0,4]→false
Constraints#
1 <= n <= 10^4.
Approach#
Walk left to right tracking farthest = max(farthest, i + nums[i]). If i > farthest, we’re stuck. Stop early if farthest >= n - 1.
Solution#
class Solution {public: bool canJump(vector<int>& nums) { int farthest = 0; for (int i = 0; i < (int)nums.size(); ++i) { if (i > farthest) return false; farthest = max(farthest, i + nums[i]); } return true; }};func canJump(nums []int) bool { farthest := 0 for i := 0; i < len(nums); i++ { if i > farthest { return false } if i+nums[i] > farthest { farthest = i + nums[i] } } return true}from typing import List
class Solution: def canJump(self, nums: List[int]) -> bool: farthest = 0 for i in range(len(nums)): if i > farthest: return False if i + nums[i] > farthest: farthest = i + nums[i] return Truefunction canJump(nums) { let farthest = 0; for (let i = 0; i < nums.length; i++) { if (i > farthest) return false; if (i + nums[i] > farthest) farthest = i + nums[i]; } return true;}class Solution { public boolean canJump(int[] nums) { int farthest = 0; for (int i = 0; i < nums.length; i++) { if (i > farthest) return false; farthest = Math.max(farthest, i + nums[i]); } return true; }}function canJump(nums: number[]): boolean { let farthest = 0; for (let i = 0; i < nums.length; i++) { if (i > farthest) return false; if (i + nums[i] > farthest) farthest = i + nums[i]; } return true;}Editorial#
Greedy on reachability. We never need to “choose” a jump distance — if any earlier index can reach i, we can be there, and from there we can extend the reach as far as i + nums[i]. The only failure mode is i > farthest, which means a zero (or short jump) blocked us.
Complexity#
- Time: O(n).
- Space: O(1).
Concept revision#
Related#