Simple Javascript solution with early break

  • 1

    The aim is just to go right, one by one, and only remember the farthest reachable index. As soon as we detect than we cannot advance anymore (maxIndex === currentIndex), we can stop asap, no need to check remaining numbers.

    function canJump(nums) {
        let maxReachableIndex = 0;
        for (let i = 0; i < nums.length; ++i) {
            maxReachableIndex = Math.max(maxReachableIndex, i + nums[i]);
            if (maxReachableIndex === i) { break; }
        return maxReachableIndex >= nums.length - 1;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.