Mediumgreedy
Jump Game
Problem (restated)
From index 0, each nums[i] is max jump length. Return whether you can reach the last index.
Intuition
Track farthest reachable index; if i exceeds far, stuck.
Approaches
Farthest reach
Tested onlyTime O(n)Space O(1)
Idea. far = max(far, i + nums[i]); fail if i > far.
Walkthrough. [2,3,1,1,4] far grows to end → true; [3,2,1,0,4] stuck at 0 → false.
Trade-offs. Greedy O(n) vs DP reachability O(n²).
Solution
export function canJump(nums: number[]): boolean {
let far = 0;
for (let i = 0; i < nums.length; i++) {
if (i > far) return false;
far = Math.max(far, i + nums[i]!);
if (far >= nums.length - 1) return true;
}
return true;
}
export function canJump(nums: number[]): boolean {
let far = 0;
for (let i = 0; i < nums.length; i++) {
if (i > far) return false;
far = Math.max(far, i + nums[i]!);
if (far >= nums.length - 1) return true;
}
return true;
}
Template connection
Greedy farthest reach.
Reflection
- Which pattern gave this away within 90 seconds?
- What changed from the standard template?
- What would break the current solution?