Jump Game

Medium

Topics
ArrayGreedyDynamic Programming

Given an array nums where each element is your maximum jump length from that position, return true if you can reach the last index.

Example 1

20start31121344
start and goal
Each cell is the maximum jump from that position, not a fixed one, so a position is reachable whenever some earlier jump clears it. That frontier never falls behind the current index here, so the end is reachable and the answer is true.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [2,3,1,1,4]
Output: true

Example 2

30start21120344
cannot be reached
Here the frontier stalls before index 4, which nothing can clear, so the answer is false.
Input:  nums = [3,2,1,0,4]
Output: false

Constraints

  • 1 <= nums.length <= 10^4
  • 0 <= nums[i] <= 10^5
Editorial — intuition, approach, complexity and pitfalls

Intuition

Instead of trying jumps, track the farthest index reachable so far. As long as you never stand on an index beyond that reach, you can keep going; the moment an index exceeds the reach, you are stuck.

Approach

  1. Keep reach = 0.
  2. Scan indices; if i > reach, return False.
  3. Otherwise extend reach = max(reach, i + nums[i]).
  4. Finishing the scan means the end is reachable.

Walkthrough

nums = [3, 2, 1, 0, 4]
i=0 reach=3
i=1 reach=3
i=2 reach=3
i=3 reach=3
i=4 4>reach -> False

Complexity

  • Time — O(n): single greedy pass.
  • Space — O(1): one variable.

Common Pitfalls

  • Keep the i > reach check. Without it the loop keeps updating reach from indices it can never actually stand on, and every input returns true -- including [3,2,1,0,4], which is genuinely unreachable.
  • reach is a maximum, not a running total. Adding jump lengths together assumes you take every jump at full length, which is not what the problem allows.

Full Solution — all languages

class Solution:
    def canJump(self, nums):
        reach = 0
        for i, x in enumerate(nums):
            if i > reach:
                return False
            reach = max(reach, i + x)
        return True
SensAI
Beta
Tap the mic to stop voice mode