2 minute read

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.

/**
 * @param {number[]} nums
 * @return {boolean}
 */
var canJump = function (nums) {
  // Initialize a variable to keep track of the maximum reachable position.
  let maxNum = 0;

  // Iterate through the array.
  for (let i = 0; i < nums.length; i++) {
    // Check if the current index is beyond the maximum reachable position.
    if (i > maxNum) {
      // If true, it means we cannot reach the end, so return false.
      return false;
    }
    // Update the maximum reachable position by taking the maximum of the current maximum and the sum of the current index and its jump length.
    maxNum = Math.max(maxNum, i + nums[i]);
  }

  // If we successfully iterate through the array without returning false, it means we can reach the end, so return true.
  return true;
};

The function canJump takes an array nums as input and returns a boolean (true if you can reach the last index, and false otherwise).

A variable maxNum is initialized to keep track of the maximum reachable position.

The code then enters a loop that iterates through the array using the index i.

Inside the loop, there’s a check to see if the current index i is beyond the maximum reachable position (i > maxNum). If it is, this means you can’t proceed further, so the function returns false.

If the current index i is within or before the maximum reachable position, it updates the maxNum to the maximum value between the current maxNum and the sum of the current index i and the jump length at that position (i + nums[i]).

After the loop completes, if you’ve successfully looped through the entire array without hitting a position that is beyond the maximum reachable position, it means you can reach the last index, so the function returns true.

The time complexity of this algorithm is O(n), where n is the length of the input array ‘nums’, as it iterates through the array once.

Leave a comment