15% off all plans & roadmaps Use code

See plans

Jump Game

Updated

TL;DR: You start at index 0 and each value is your maximum jump length. Track the furthest index you can reach as you scan left to right, and fail the moment the scan passes that frontier.

Problem

You are given an integer array nums. You start at the first index, and each element tells you the maximum jump length from that position.

Return true if you can reach the last index, or false otherwise.

Example 1

Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to index 1, then 3 steps to the last index.

Example 2

Input: nums = [3,2,1,0,4]
Output: false
Explanation: Every path ends at index 3. Its maximum jump length is 0, so you can never move on to the last index.

Constraints

  • 1 <= nums.length <= 10^4
  • 0 <= nums[i] <= 10^5

Constraints that matter

  • nums.length up to 10^4 means an O(n^2) scan does about 10^8 basic steps in the worst case. That is borderline, so a linear solution is the safe target.
  • Plain recursion that tries every jump length is exponential in n. With n up to 10^4 it cannot finish, so you must stop re-exploring the same index.
  • nums[i] can be 0, so a zero is a possible dead end. A zero only blocks you if no earlier cell can jump over it.
  • nums[i] can reach 10^5 while n is at most 10^4. Clamp every jump to the last index so you never walk past the array.
  • nums.length can be 1. You already stand on the last index, so the answer is true even when nums[0] is 0.

View on LeetCode

Hints

Hint 1

This is a greedy reachability problem.

Hint 2

The most literal solution is recursion: from index i, try every jump length from 1 to nums[i] and recurse.

Solution

Intuition

This is a greedy reachability problem. The key fact is that the set of reachable indices has no holes. If you can stand on index i and nums[i] is k, you can also stand on every index from i + 1 to i + k, because a jump of any smaller length is allowed.

Picture a line of stepping stones where you only carry one flag marking the farthest stone you have reached. The flag is the variable reach, the walking is the scan, and you stop the moment you find a gap past the flag.

That means you never need to remember which path got you to an index. You only need one number: the furthest index reached so far. Call it reach. Everything from 0 to reach is reachable, and everything past it is not, as far as you know.

Scan left to right. At index i, if i > reach, you have found a gap. Nothing before i can jump that far, and indices past i are only reachable through indices you can stand on, so the end is out of reach. Otherwise i is reachable, so update reach = max(reach, i + nums[i]).

You can also see the problem as a graph. Each index has edges to the next nums[i] indices, and you ask whether the last node is reachable from node 0. A DFS or BFS answers that in O(n^2) edges.

Plain recursion without a visited set explores the same index through many routes, which is where the exponential blow-up comes from. The greedy scan works because the contiguous-range property collapses all those routes into one number.

Watch the pattern animation

Worked example

Input: nums = [6, 0, 0, 0, 0, 0, 1]
Output: true
Explanation: The first cell allows a jump of up to 6 steps, and the last index is exactly 6 steps away. The five zeros in the middle never matter because you jump over all of them in one move.

Approach 1: Brute force: mark every reachable index

The most literal solution is recursion: from index i, try every jump length from 1 to nums[i] and recurse. Without memory this repeats work. Index 5 may be reached through hundreds of different routes, and each route re-explores everything after it. The running time is exponential in n.

The cheapest fix that keeps the same spirit is to remember which indices you have already reached. Keep a boolean array reach. Walk the indices in order, and for every reachable index mark each cell it can jump to. That is the DFS or BFS over the index graph with a visited set, written as a loop.

Steps

  1. Create a boolean array reach of length n, all false, and set reach[0] to true.
  2. Loop i from 0 to n - 1.
  3. If reach[i] is false, skip it, because you cannot stand there.
  4. Compute end = min(n - 1, i + nums[i]) so the jump never leaves the array.
  5. Mark every index from i + 1 to end as reachable.
  6. After the loop, return reach[n - 1].

Dry run

Trace on nums = [6, 0, 0, 0, 0, 0, 1], n = 7.

  • Start: reach = [T, F, F, F, F, F, F].
  • i = 0: reachable. end = min(6, 0 + 6) = 6. Mark indices 1 to 6, so every entry becomes true.
  • i = 1 to 5: each is reachable, but nums[i] is 0, so the range i + 1 to end is empty and nothing changes.
  • i = 6: reachable, end = min(6, 7) = 6, nothing to mark.
  • reach[6] is true, so the answer is true.

Complexity

TimeO(n^2)
SpaceO(n)

Here n is the array length. The outer loop visits each index once, and each visit marks at most n - 1 later cells, so the work is at most n * n. The reach array holds n booleans, which is the only extra memory.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        n = len(nums)
        reach = [False] * n
        reach[0] = True
        for i in range(n):
            if not reach[i]:
                continue
            end = min(n - 1, i + nums[i])
            if end > i:
                # mark every cell this jump can land on
                reach[i + 1:end + 1] = [True] * (end - i)
        return reach[n - 1]

Approach 2: Backward DP: good indices

What's slow: the forward version marks the same cell many times. Index 6 above gets marked by index 0 and could be marked again by every later index that can reach it. Each cell is written once per index that can jump to it.

The insight that fixes it: flip the question. Ask, for each index, whether the last index is reachable from there. Call such an index good. The last index is good, and an earlier index is good if at least one cell in its jump range is good. Fill the table from right to left, so every answer you need is already known. Stop scanning a range at the first good cell.

Steps

  1. Create a boolean array good of length n, all false, and set good[n - 1] to true.
  2. Loop i from n - 2 down to 0.
  3. Compute furthest = min(n - 1, i + nums[i]).
  4. Check the cells i + 1 to furthest in order and stop at the first good one.
  5. If you found a good cell, set good[i] to true.
  6. Return good[0].

Dry run

Trace on nums = [6, 0, 0, 0, 0, 0, 1], n = 7.

  • Start: good[6] = T, all others false.
  • i = 5: nums[5] = 0, so the range 6 to 5 is empty. good[5] = F.
  • i = 4, 3, 2, 1: each has nums[i] = 0, so each stays false.
  • i = 0: furthest = min(6, 6) = 6. Scan indices 1 to 6. Indices 1 to 5 are false, index 6 is good. good[0] = T.
  • Return good[0], which is true.

Complexity

TimeO(n^2)
SpaceO(n)

Here n is the array length. Each of the n - 1 indices scans at most n - 1 cells to its right, so the time is at most n * n. The early stop helps on many inputs but does not change the worst case. The good array stores n booleans.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        n = len(nums)
        good = [False] * n
        good[n - 1] = True
        for i in range(n - 2, -1, -1):
            # good if any cell in the jump range is good
            good[i] = any(good[i + 1:i + nums[i] + 1])
        return good[0]
Jump Game Reachability/Minimization pattern infographic for Jump Game

Solution pattern

Jump Game Reachability/Minimization

Part of Greedy Patterns

Approach 3: Greedy furthest reachOptimalJump Game Reachability/Minimization

What's slow: both earlier versions store a table and rescan jump ranges. The table answers more than the problem asks. You do not need to know which individual cells are reachable or good.

The insight that fixes it: reachable cells always form the prefix 0 to reach. One integer describes that whole prefix. Scan once, extend reach with i + nums[i] at every reachable i, and return false when the scan index passes reach. Each index costs one comparison and one max.

Steps

  1. Set reach = 0, the furthest index known to be reachable.
  2. Loop i from 0 to n - 1.
  3. If i > reach, index i is cut off from the start, so return false.
  4. Update reach = max(reach, i + nums[i]).
  5. If the loop ends, every index was reachable, so return true.
  6. Optional: return true as soon as reach >= n - 1 to skip the rest of the scan.

Dry run

Trace on nums = [6, 0, 0, 0, 0, 0, 1], n = 7, last index 6.

inums[i]i > reach?i + nums[i]reach after
start0
060 > 0 no66
101 > 6 no16
202 > 6 no26
303 > 6 no36
404 > 6 no46
505 > 6 no56
616 > 6 no77

The loop finishes without a gap, so the answer is true. With the early exit, you would return at i = 0, because reach = 6 already equals the last index.

On [3, 2, 1, 0, 4], reach stays 3 through i = 3. At i = 4 the check 4 > 3 fires and you return false.

Complexity

TimeO(n)
SpaceO(1)

Here n is the array length. The loop runs at most n times and each pass does one comparison and one max, so the time is O(n). The only state is the integers reach and i, so the space is O(1) no matter how large the array is.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        reach = 0
        for i, jump in enumerate(nums):
            if i > reach:
                return False  # gap: index i cannot be reached
            reach = max(reach, i + jump)
        return True

Common mistakes

  • Returning false when nums[i] == 0. A zero only matters if i == reach at that moment. An earlier cell may already jump over it, so test i > reach instead.
  • Updating reach = max(reach, i + nums[i]) before the if i > reach check. You then let an unreachable index extend the frontier. Check first, update second.
  • Writing reach = i + nums[i] without the max. A small jump at a later index can shrink the frontier below what an earlier cell already achieved. Always keep the larger value.
  • Starting reach at nums[0] and looping from index 1 without care. This breaks single-element input like [0] and makes the off-by-one checks harder. Start reach = 0 and loop from index 0.
  • Using if i >= reach for the failure test. Standing exactly on the frontier is fine because that index is reachable. Only i > reach is a gap.
  • Writing plain recursion with no memo or visited array. It repeats the same indices through many routes and runs in exponential time on inputs like [1,1,1,...,0]. Record results per index or use the greedy scan.

Edge cases

  • [0]: one element, you already stand on the last index. Expected true.
  • [0, 1]: the first cell cannot move. Expected false, because i = 1 exceeds reach = 0.
  • [1, 0, 1]: the zero in the middle is the frontier, so index 2 is cut off. Expected false.
  • [2, 0, 0]: the first jump lands on or passes the zeros and reaches the end. Expected true.
  • [100000, 0, 0]: the jump is far larger than the array. Expected true, and brute-force code must clamp the range to the last index.
  • [1, 1, 1, ..., 1] with 10^4 ones: every step is needed. Expected true, with reach growing by one each step.

Follow-ups interviewers ask

How would you return the minimum number of jumps instead of true or false?
That is Jump Game II. Treat the array as BFS levels. Track the end of the current level and the furthest index seen so far. When the scan reaches the level end, add one jump and move the level end to the furthest index. It is still O(n) time and O(1) space.
Can you reconstruct an actual path of jumps, not just a boolean?
Yes. Store for each index the earlier index that first reached it, or keep a parent array in the forward marking version. For the greedy scan, record the index that produced each new reach value. Then walk back from the last index. This costs O(n) extra space for the parent array.
What changes if jumps must be exact instead of at most nums[i]?
The contiguous-range property breaks, so greedy no longer works. From i you can only land on i + nums[i] or a specific set of cells. Now it is plain graph reachability, so run DFS or BFS over the index graph with a visited array in O(n) time and O(n) space.

Jump Game FAQ

What is the time complexity of Jump Game?

The greedy solution is O(n) time and O(1) space, where n is the array length. It scans each index once and does constant work per index. The brute force marking and backward DP versions are O(n^2) time and O(n) space.

Why use a greedy approach for Jump Game?

Because reachable indices always form a prefix from 0 to some furthest index. A jump of length k also allows every shorter jump, so there are no holes. That lets one integer, reach, replace a whole table of reachable cells.

Can Jump Game be solved with dynamic programming?

Yes. Define good[i] as whether the last index is reachable from i, and fill the table from right to left. Each entry looks at its jump range, so the cost is O(n^2) time and O(n) space. A top-down version with memoization has the same bounds but uses recursion depth up to n, which is risky in Python.

Why does plain recursion time out on Jump Game?

The recursion tree tries every jump length from every index, and the same index is reached through many different routes. The number of routes grows exponentially with n. A memo or visited array cuts it to O(n^2), and the greedy scan cuts it to O(n).

Can Jump Game be solved in O(1) extra space?

Yes. The greedy scan keeps only the integers reach and i. It does not modify the input and needs no table.

Can BFS or DFS solve Jump Game?

Yes. Treat each index as a node with edges to the next nums[i] indices and search from node 0 for the last node. With a visited set this is O(n^2) in the worst case because the edge count can be quadratic. It is correct but slower than the greedy scan.

Asked at

See which companies ask this — Pro

Practise it