← DSA
MEDIUM

Jump Game

PracticeNeetCode ↗LeetCode ↗

Given an integer array nums where each element is the maximum jump length from that position, determine whether you can reach the last index starting from index 0.

Example

Input nums = [2,3,1,1,4]
Output true

Key Pointers

Step-by-Step Analysis

  1. Initialize farthest = 0.
  2. For each index i, value n in nums: if i > farthest, return False — this index can't be reached.
  3. Otherwise update farthest = max(farthest, i + n).
  4. If the loop completes, return True.

Complexity

Time: O(n) — Space: O(1)

Code

def canJump(nums: list[int]) -> bool:
    farthest = 0
    for i, n in enumerate(nums):
        if i > farthest:
            return False
        farthest = max(farthest, i + n)
    return True

Code Explanation

How the solution above works, piece by piece.

  1. farthest = the furthest index reachable so far.
  2. Walk left to right. If i > farthest, index i can't be reached, so neither can the end → False.
  3. Otherwise, from i you can reach i + nums[i]; update farthest.
  4. If the loop finishes, every index (including the last) was reachable → True.
  5. One pass, O(1) space: no need to know which jumps, only how far they can get.

Visual Walkthrough

Running it on nums = [2, 3, 1, 1, 4]:

trace2031121344i=0reach up to index 223114i=1reach up to index 4 ≥ last → can finish23114i=2reach up to index 4 ≥ last → can finish23114i=3reach up to index 4 ≥ last → can finish23114i=4reach up to index 8 ≥ last → can finish
Blue marks everything reachable so far. From index 1 (value 3) the reach already covers the last index, so the answer is True.
current indexreachable

Video Explanation

NeetCode — Greedy, LeetCode 55