Boss lesson · Unit 04
Jump game
One number, the furthest reach, decides everything
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.
Correct answer
No: every route gets stuck at index 3
Why
From index 0 you can land on 1, 2 or 3. From 1 you reach at most 3, from 2 at most 3, and index 3 holds a 0. Nothing gets past index 3. A jump may always be shorter than the number, so "too long" is never a problem.
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 Truefunction 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.