Each day I solve several coding challenges and puzzles from Codr’s ranked mode. The goal is to reach genius rank, along the way I explain how I solve them. You do not need any programming background to get started, and you will learn a ton of new and interesting things as you go.

function canJump(nums) {
  let max = 0; 
  for(let i = 0; i < nums.length; i++) {
      if (max < i) return false; 
      max = Math.max(nums[i] + i, max);
  }
  return max >= nums.length - 1
}
let A = canJump([5,0,0,6,4,6]);
// A = ? (boolean)

This challenge’s code is pretty short, let’s see what it’s all about. We have to figure out A’s boolean value:

let A = canJump([5,0,0,6,4,6]);

On first sight I have no clue what the function canJump does, so we’ll have to analyze it more closely.

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

These three lines of code are doing the following: iterating over each number in the array nums; checking if max is lesser than i, if so the function immediately returns falsely; finally it determines the new max value. The if-condition actually ensures that the max jump size is greater than current index i of the for-loop.

This algorithm is actually about determining if it’s able to “jump” to a certain position, where each number represents the max jump length.

The last line of code reveals its final condition:

return max >= nums.length - 1

It checks if max is greater or equal to nums’ array size, meaning this whole algorithm checks if one can reach the end of the array starting at the first index.

#computer-science #development #programming #javascript #coding

Road to Genius: advanced
1.05 GEEK