Skip to content
ΣDSA Patterns
Menu
Language

Greedy

Guide 2 of 6 · Path 2 of 6

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

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 only
Time 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