This visualization was AI-generated. For the original problem, visit LeetCode #55.

Jump Game

Determine if you can reach the last index of an array by jumping from each position, where each element represents your maximum jump length at that position.

Greedy LeetCode 55 ↗ Medium

Problem

You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.

Return true if you can reach the last index, or false otherwise.

Example 1:

Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.

Interactive Visualization

Jump Game Visualization
Ready to start
Current Index (i)
-
Jump Length
-
Potential Reach (i + nums[i])
-
Max Reach
0
fun canJump(nums: IntArray): Boolean {    var maxReach = 0        for (i in nums.indices) {        if (i > maxReach) {            return false        }        maxReach = maxOf(maxReach, i + nums[i])        if (maxReach >= nums.size - 1) {            return true        }    }        return true}

Status

Click "Step" or "Play" to begin

Execution Log

Waiting to start...

Explanation

Key Insight

The greedy approach tracks the farthest reachable index as we iterate through the array. At each position, we update the maximum reach based on the current position plus its jump length. If we ever encounter a position beyond our reach, we know it's impossible to complete the journey. If the maximum reach extends to or beyond the last index, we've succeeded.

Algorithm

  1. Initialize max_reach = 0 to track the farthest index we can reach
  2. Iterate through each index i in the array:
    • If i > max_reach, we've reached a position we can't access - return False
    • Update max_reach = max(max_reach, i + nums[i]) - the farthest we can reach from position i
    • If max_reach >= len(nums) - 1, we can reach the end - return True
  3. If we complete the loop without returning, we can reach the end - return True

Complexity Analysis