Jump game

Medium TimeO(n) SpaceO(1)

Index 0 of an array nums is the starting point, and the value at an index is the most steps a jump forward from it may cover — any shorter distance will do too, and every jump goes forward. Return true when the last index can be reached and false when it cannot. The values are zero or greater, and an array of one element is already at its end.

Examples

Example 1

Input
nums = [2, 3, 1, 1, 4]
Output
true
From index 0 jump 1 to the 3, which reaches index 4 outright.

Example 2

Input
nums = [3, 2, 1, 0, 4]
Output
false
Index 3 holds 0 and nothing jumps past it, so index 4 is out of reach.

The Code

function canJump(nums) {
  let reach = 0;
  for (let i = 0; i < nums.length; i++) {
    if (i > reach) return false;
    const jumpTo = i + nums[i];
    if (jumpTo > reach) reach = jumpTo;
  }
  return true;
}
canJump([2, 3, 1, 1, 4]);
Done
Step through canJump([2, 3, 1, 1, 4]) call by call