Skip to content
DSA Patterns
Menu
Language
GreedyLC #552 of 6← PreviousNext →

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

Unverified
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

far is the farthest index reachable so far, max(far, i + nums[i]). If i moves past far, the end is unreachable.

Reflection

  • reach is the farthest index seen so far. i > reach means you cannot land on i, so the answer is false.
  • A 0 that does not move reach sticks you. A 0 on the last cell is still true when reach already covers that cell.
  • [0] is true. [1,0,0] cannot reach index 2.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Jump Game: from index 0, nums[i] is the max jump length. Can we reach the end?

2
0
3
1
1
2
1
3
4
4

far = 0

Key:CurrentActive rangeMatchSettledEliminated