Table of Contents
Open Table of Contents
Description
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.
Constraints:
Approach
We can use a greedy algorithm. The idea is to keep track of the farthest index we can reach as we iterate through the array. If at any point the current index exceeds the farthest reachable index, it means we cannot proceed further, and we should return false. If we can reach or exceed the last index, we return true.
Solution
/**
* @param {number[]} nums
* @return {boolean}
*/
var canJump = function (nums) {
// The farthest index we can currently reach
let farthestReach = nums[0];
// Iterate through the array up to the farthest reachable index
for (let i = 0; i <= farthestReach; i++) {
// Update the farthest reachable index
farthestReach = Math.max(farthestReach, i + nums[i]);
// If we can reach or pass the last index, return true
if (farthestReach >= nums.length - 1) return true;
}
// If we finish the loop without reaching the end, return false
return false;
};
Complexity Analysis
Time Complexity
The time complexity is , where is the length of the input array nums.
Space Complexity
The space complexity is as we only use a constant amount of extra space to store the farthestReach variable, regardless of the input size.