Browse curriculum

FAANGPrep Sprint

Jump Game

Determine if you can reach the last index.

Examples

Input:nums = [2,3,1,1,4]
Output:true
Explain:

From index 0 move 1 place to index 1; its value of 3 then reaches the last index.

Input:nums = [3,2,1,0,4]
Output:false
Explain:

Every path lands on index 3, whose jump length is 0, so index 4 is never reached.

Input:nums = [0]
Output:true
Explain:

You start on the last index, so there is nothing to jump.

Problem Understanding

You are given an array nums. nums[i] is the maximum jump length from that position. Return true if you can reach the last index.

Strategy

Track the furthest index reachable so far.

  1. Start with reachable = 0 — the index you begin on.
  2. Walk i from 0 upward.
  3. If i > reachable, nothing can land on i: return false.
  4. Otherwise update reachable = max(reachable, i + nums[i]).
  5. As soon as reachable reaches the last index, return true.

Interactive Visualization

✓ = REACHABLE · THE MARKS ARE ALWAYS A PREFIX · OUTLINED = HOW FAR THIS JUMP CAN LAND

START ON INDEX 0

0

1

2

3

4

jump

2
3
1
1
4

reach

✓

furthest reachable

0

last index

4

Answer

—

the rule

past the frontier → false
frontier = the further of itself and i + jump
frontier covers the last index → true

 

You start on index 0, so the furthest reachable index is 0. The goal is index 4

Next

Visit index 0, which can jump up to 2

nums

The top row is the jump length at each index; the bottom row marks every index known to be reachable. The marks are always a prefix — which is exactly why one number, the frontier, can stand for all of them. The index being visited is filled, and the furthest cell its jump can land on is outlined.

Try Example 2: every path lands on the 0 at index 3, and the walk stops at index 4, past the frontier.