Bitpath

Boss lesson · Unit 04

Jump game

One number, the furthest reach, decides everything

13 exercisesabout 3 min

What you practise

  • Jump game with farthest reach
  • A case where greedy fails

Try a question from this lesson

Pick one

Each number is the furthest you may jump forward from that position. Starting at index 0 of [3, 2, 1, 0, 4], can you reach the last index?

Hint

For each index you can land on, write down the furthest index it reaches. Compare the best of those with the last index.

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Boss: the jump game

Each number in a list says how far you may jump forward from that position, at most. You start at index 0. Can you reach the last index?

[2, 3, 1, 1, 4]: yes, for example 0 → 1 → 4. [3, 2, 1, 0, 4]: no, every route ends on the 0 at index 3.

Trying every route takes exponential time. One greedy number is enough.

Concept

Track the furthest reach

Keep one number, reach: the furthest index you could stand on so far.

Walk the list. If you arrive at an index beyond reach, you cannot be there: the answer is no. Otherwise this position may push reach further, to its index plus its jump length. If the walk finishes, the answer is yes.

def can_jump(nums):
    reach = 0
    for i, x in enumerate(nums):
        if i > reach:
            return False
        reach = max(reach, i + x)
    return True
function canJump(nums) {
  let reach = 0;
  for (let i = 0; i < nums.length; i++) {
    if (i > reach) return false;
    reach = Math.max(reach, i + nums[i]);
  }
  return true;
}
function canJump(nums: number[]) {
  let reach = 0;
  for (let i = 0; i < nums.length; i++) {
    if (i > reach) return false;
    reach = Math.max(reach, i + nums[i]);
  }
  return true;
}

Python notePython spells the two truth values with capitals: True and False.

TypeScript noteNo return type is written. TypeScript sees return false and return true and infers boolean.

10 more exercises in the app

  • 2× type the answer
  • 2× fill the blanks
  • 4× multiple choice
  • 1× true or false
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy