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.
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
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
Execution Log
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
- Initialize
max_reach = 0to track the farthest index we can reach - Iterate through each index
iin the array:- If
i > max_reach, we've reached a position we can't access - returnFalse - Update
max_reach = max(max_reach, i + nums[i])- the farthest we can reach from positioni - If
max_reach >= len(nums) - 1, we can reach the end - returnTrue
- If
- If we complete the loop without returning, we can reach the end - return
True
Complexity Analysis
- Time Complexity: O(n) - We traverse the array once
- Space Complexity: O(1) - Only using a single variable to track max reach