Jump Game Medium 0 attempts
LeetCode ↗

Jump Game

Medium ArrayTwo Pointers LeetCode

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.

Sample Input
nums = [2,3,1,1,4]
Sample Output
true
Constraints
  • 1 <= nums.length <= 10^4
  • 0 <= nums[i] <= 10^5
Test Cases
Case 1
Args: [[2,3,1,1,4]] Expected: true

Iterate through the array while maintaining the farthest index you can reach. If you ever land on an index beyond your current reach, return false. Otherwise, update your reach as max(maxReach, i + nums[i]).

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)

Saved in this browser only. Private to you.

JavaScript