Skip to problem
←

Jump Game

Medium 0 attempts

Starting at index 0, determine whether you can reach the final index of nums. From index i, you may jump forward any positive number of positions up to nums[i]; you do not have to use the maximum length.

A zero prevents further movement from that index, but does not matter if it is already the destination. A one-element array is therefore always reachable. Return a boolean.

Function contract

nums is a nonempty array of nonnegative maximum jump lengths. You begin at index 0.

Output: Return true if the last index is reachable, otherwise false.

Example 1

Input
nums = [2,3,1,1,4]
Output
true

Explanation: Jump from index 0 to index 1, then from index 1 to index 4.

Example 2

Input
nums = [3,2,1,0,4]
Output
false
Constraints
  • 1 <= nums.length <= 10^4
  • 0 <= nums[i] <= 10^5
Topics

Iterate through the array while maintaining the farthest index you can reach. If the scan reaches an index beyond this boundary, return false. Otherwise, update your reach as max(maxReach, i + nums[i]).

javascript
function canJump(nums) {
  let maxReach = 0;

  for (let i = 0; i < nums.length; i++) {
    if (i > maxReach) return false;
    maxReach = Math.max(maxReach, i + nums[i]);
  }

  return true;
}

Time: O(n) Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript