Skip to content
Problem 55 · LeetCode 55(opens in a new tab)

Jump Game

MediumArrays

You get an array of whole numbers, nums, and you start on index 0. The value at each index is the longest jump you may make from it: from index i you can move forward to any index from i + 1 to i + nums[i].

Return true if some sequence of jumps lands you on the last index, and false if it cannot be done.

Example 1

Input:  nums = [1, 3, 0, 1, 2]
Output: true
Why:    0 → 1, then a jump of 3 lands on index 4
2 more examples and the constraints

Example 2

Input:  nums = [2, 1, 0, 3]
Output: false
Why:    every route ends on index 2, which holds 0

Example 3

Input:  nums = [0]
Output: true
Why:    index 0 is already the last index

Constraints

  • 1 ≤ length of nums ≤ 10,000
  • 0 ≤ nums[i] ≤ 100,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Good indexes, right to left (DP)O(n²)
  2. Greedy furthest reachO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 numbersVerdict
Good indexes (DP)O(n²)
Correct, but slow on long arrays
Greedy furthest reachO(n)
Best; one pass, no extra memory

n = length of nums.

Edge cases to test

  • One element. [0] is already at the end, so the answer is true.
  • Zero at the start. [0, 1] cannot move at all: false.
  • Zero you can jump over. [2, 0, 0] lands on the last index straight from index 0: true.
  • Zero at the last index. The last value is never used, so [3, 0, 2, 0] is true.

Common mistakes

  • Assuming you must jump exactly nums[i] steps; any shorter jump is allowed too.
  • Checking i > reach after updating reach, so a dead end looks reachable.
  • Returning false as soon as you see a zero, even when an earlier index jumps past it.

How to talk through it

  1. 1Clarify. Is nums[i] the exact jump or the longest one? Do I only need yes or no, not the route?
  2. 2Give the DP. Mark indexes that can reach the end, right to left. Say it is O(n²) in the worst case.
  3. 3Spot the block. Reachable indexes form one block from 0, so a single number, the furthest reach, says everything.
  4. 4Code the greedy. Check i against reach before stretching it, and say why the order matters.
  5. 5Test out loud. Run [0], [0, 1] and a zero you can jump over.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?