Skip to content

Jump Game

Decide whether you can hop from the first index to the last, tracking only the farthest reachable index.

MediumGreedy
Solve on LeetCode

The problem

You stand on index 0 of an array nums, and nums[i] is the longest jump you can make from index i; any shorter jump is allowed too. Return true if you can reach the last index.

Input nums = [1, 3, 0, 0, 2, 0]

Output true

Jump 1 to index 1, then 3 to index 4, then 1 to index 5.

Input nums = [2, 1, 0, 3]

Output false

Indexes 0, 1 and 2 reach no farther than index 2, which holds 0, so index 3 is out of reach.

Key constraint: There are up to 10,000 indexes and jumps of up to 100,000, so trying jump sequences is hopeless, but one pass is cheap.

How to spot the pattern

  • You only need a yes or no about reaching the end.
  • The indexes you can reach always form one unbroken stretch from the start.

The idea

If you can reach some index, you can reach every index before it, so all that matters is how far the reachable stretch goes. Walk from left to right keeping farthest, the largest i + nums[i] among the indexes you can reach. If you ever stand on an index beyond farthest, there is a gap you can't cross; if that never happens, the last index is reachable.

Brute force: Try every jump length from every index recursively, which takes exponential time.

Step by step

  1. 1Start with farthest = 0.
  2. 2Walk through the indexes in order.
  3. 3If the index i is greater than farthest, return false, because nothing before it can reach it.
  4. 4Otherwise set farthest = max(farthest, i + nums[i]).
  5. 5If the loop finishes, return true.

See the pattern move

The greedy pattern on a small example. Step through it, or press play.

Code

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        farthest = 0  # farthest index you can reach from the indexes seen so far
        for i, jump in enumerate(nums):
            if i > farthest:
                return False  # no earlier index reaches i, so nothing after it is reachable
            farthest = max(farthest, i + jump)
        return True

Complexity

Time

O(n)

Space

O(1)

One pass with a single variable.

Watch out for

  • Always making the longest jump: in [2, 3, 1, 0, 4] that lands on the 0, while a jump of 1 and then 3 works.
  • Treating every 0 as a dead end: a 0 only matters when nothing before it can jump past it.

Follow-up questions

What if you need the fewest jumps?

Scan in windows of indexes reachable with the same number of jumps, which is Jump Game II.

Can you solve it from the back?

Yes. Keep goal, the leftmost index known to reach the end, starting at the last index, and move it to i whenever i + nums[i] >= goal while walking right to left. The answer is whether goal ends at 0.

In Hinglish

Bas itna yaad rakho ki ab tak sabse door kahan tak pahunch sakte ho. Agar koi index us limit se aage nikal gaya, toh wahan tak pahunchne ka raasta hi nahi hai.

Related problems