Mediumgreedy
Jump Game II
Problem (restated)
Minimum jumps to reach last index (guaranteed reachable).
Intuition
Level-by-level: within current jump range, track farthest next end; when i hits end, jump++.
Approaches
Range BFS greedy
Tested onlyTime O(n)Space O(1)
Idea. curEnd, far; when i==curEnd, jumps++, curEnd=far.
Walkthrough. [2,3,1,1,4] → 2 jumps.
Trade-offs. Greedy levels vs DP min jumps O(n²).
Solution
export function jump(nums: number[]): number {
let jumps = 0, curEnd = 0, far = 0;
for (let i = 0; i < nums.length - 1; i++) {
far = Math.max(far, i + nums[i]!);
if (i === curEnd) {
jumps++;
curEnd = far;
}
}
return jumps;
}
export function jump(nums: number[]): number {
let jumps = 0, curEnd = 0, far = 0;
for (let i = 0; i < nums.length - 1; i++) {
far = Math.max(far, i + nums[i]!);
if (i === curEnd) {
jumps++;
curEnd = far;
}
}
return jumps;
}
Template connection
Greedy jump with range expansion.
Reflection
- Which pattern gave this away within 90 seconds?
- What changed from the standard template?
- What would break the current solution?