CodeArchon

mediumGreedyAmazonGoogle

Last-Tile Reacher

A platformer character on tile 0 jumps up to nums[i] tiles from tile i. Can they reach the last tile?

Given a non-negative array nums where nums[i] is the max jump length from index i, determine if you can reach the last index starting from index 0.

Choose approach

2
0
i
3
1
1
2
reach
1
3
4
4
1/6
Narrationstep 1 of 6

i=0: reach = max(2, 0+2) = 2.

1def canJump(nums):
2 reach = 0
3 for i, v in enumerate(nums):
4 if i > reach: return False
5 reach = max(reach, i + v)
6 return True
Variables
i=0
reach=2

How to think about it

  1. Only need to know farthest reachable index so far.
  2. Zero jump length blocks progress unless already past it.

Edge cases to catch in interview

  • Single element -> true.
  • Zero in path with insufficient prior reach -> false.

Examples

Example 1false
{"values":[3,2,1,0,4]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed