Jump Game II solution explained

Jump Game II asks for the fewest jumps from the first index to the last, and the fast answer is a breadth-first search done without a queue. Group the squares into bands: band 1 is every square one jump can reach, band 2 is every square reachable from band 1, and so on. The number of bands you open before covering the last index is the answer, found in one O(n) pass.

By Published 8 min read

The problem, reworded

A row of squares holds non-negative whole numbers. From square i you may move forward to any square up to hops[i] away. You start on square 0. Find the minimum number of moves needed to land on the last square. Most versions promise the last square is reachable; the code on this page returns -1 if it is not, so you can show you thought about it.

Arrays made up for this page, with answers from the code below
SquaresFewest jumpsOne shortest route
[2, 5, 1, 1, 0, 1, 1, 1]30 → 1 → 6 → 7
[3, 4, 1, 1, 1, 1, 1]30 → 1 → 5 → 6
[5, 1, 1, 1, 1, 1]10 → 5 in one hop
[0]0Already on the last square
[1, 0, 2]-1Square 1 holds 0, so square 2 is never reached
Arrays made up for this page, with answers from the code below. Scroll sideways on a small screen.

Where it shows up

Interviewers often ask this right after the reachability version, or give it alone to see whether you recognize a shortest-path problem in disguise. Each square is a node, each allowed hop is an edge, and every edge costs one jump. Unweighted shortest paths mean breadth-first search. The strong answer then notices that the graph has a special shape, so the queue can be replaced by two pointers.

Greedy on hop length is wrong

Hopping as far as possible from wherever you stand looks natural. Run it on [1, 2, 3, 1, 1, 2, 0, 1] and it travels 0 → 1 → 3 → 4 → 5 → 7, which is 5 jumps. The true minimum is 4: 0 → 1 → 2 → 5 → 7. Hopping only to square 2 from square 1 looks timid, yet square 2's hop of 3 carries you much further than square 3's hop of 1. A good greedy rule must choose the square whose own hop reaches furthest, not the square furthest away, and the band method below makes that choice automatically.

Brute force: relax every hop

Keep best[i], the fewest jumps known to reach square i. Square 0 costs 0. Walk the squares in order; for each reachable one, try every hop length and improve best at the landing square. Because jumps only go forward, every square's value is final by the time the loop reaches it. With long hops, each square touches up to n others, so the work is O(n²).

def fewest_jumps_slow(hops):
    INF = float("inf")
    best = [INF] * len(hops)
    best[0] = 0
    for i in range(len(hops)):
        if best[i] == INF:
            continue
        for step in range(1, hops[i] + 1):
            if i + step < len(hops):
                best[i + step] = min(best[i + step], best[i] + 1)
    return -1 if best[-1] == INF else best[-1]
Forward relaxation table: O(n²) worst case.

Bands instead of a queue

Look at which squares need exactly k jumps. Square 0 needs 0. The squares that need exactly 1 are 1 through hops[0]: a single unbroken run. In general, the squares needing k + 1 jumps start right after the k-jump band and end at the farthest point any square in the k-jump band can hop to. Every band is a contiguous slice that begins where the previous one ended, so you never need a queue to know what is in it.

So scan once. Keep band_end, the last square reachable with the current number of jumps, and next_end, the farthest square any square seen so far can reach. When the scan reaches band_end, the current band is finished: count one more jump and make next_end the new band_end. If next_end did not move past band_end, the next band would be empty, so the end is unreachable. Stop as soon as a band covers the last square. The loop runs only to the second-to-last square, because standing on the last square needs no further jump.

def fewest_jumps(hops):
    jumps = 0
    band_end = 0   # last square reachable with 'jumps' jumps
    next_end = 0   # last square reachable with one more jump
    for i in range(len(hops) - 1):
        next_end = max(next_end, i + hops[i])
        if i == band_end:
            if next_end == band_end:
                return -1  # stuck: the next band adds no squares
            jumps += 1
            band_end = next_end
            if band_end >= len(hops) - 1:
                break
    return jumps
Python: one pass over the squares, O(n) time and O(1) extra space.
#include <algorithm>
#include <vector>
using namespace std;

int fewestJumps(const vector<int>& hops) {
    int n = hops.size();
    int jumps = 0, bandEnd = 0, nextEnd = 0;
    for (int i = 0; i < n - 1; ++i) {
        nextEnd = max(nextEnd, i + hops[i]);
        if (i == bandEnd) {
            if (nextEnd == bandEnd) return -1;  // stuck
            ++jumps;
            bandEnd = nextEnd;
            if (bandEnd >= n - 1) break;
        }
    }
    return jumps;
}
C++: identical logic with ints.

Bands for [2, 5, 1, 1, 0, 1, 1, 1]

Each row is one band, computed by tracing the code
JumpsSquares in the bandFarthest hop from the band
002 (from square 0)
11 to 26 (square 1 hops 5)
23 to 67 (square 6 hops 1)
37The last square is covered, so stop
Each row is one band, computed by tracing the code. Scroll sideways on a small screen.

Notice that square 2, which is in band 1, contributes nothing because square 1 already reaches further. The band method never commits to a single square; it just records how far the whole band can push, which is why it cannot be fooled the way the longest-hop rule was.

Time and space

n squares
ApproachTimeExtra space
Recursion over every routeExponentialO(n) call stack
Relaxation tableO(n²) worst caseO(n)
Breadth-first search with a queueO(n²) as usually written, since each square scans its whole hop rangeO(n)
Bands with two pointersO(n)O(1)
n squares. Scroll sideways on a small screen.

Edge cases

  • One square: the answer is 0, and the loop body never runs.
  • A first hop that already covers everything: 1 jump.
  • An unreachable end: detect it when a band closes without extending past its own end. If the prompt guarantees reachability, say you are adding the check anyway.
  • Zeros inside a band are fine as long as another square in the same band reaches past them.
  • Hops larger than the remaining length: next_end can run past the last index, which the stop condition handles.

Mistakes to watch for

  • Looping through the last square too. If band_end equals the last index at that moment, the code counts an extra jump that is never taken.
  • Counting a jump every time next_end grows, instead of only when a band closes.
  • Choosing the square that is furthest away rather than the square that reaches furthest.
  • Forgetting the n = 1 case, where some versions return 1 by accident.
  • Explaining the method as just greedy without naming the bands. Calling it a breadth-first search over contiguous layers is the clearest justification.

Follow-up questions

  • Return the route, not just the count. When square i pushes next_end further, remember i as the parent of every newly covered square, then follow parents back from the end.
  • Each jump has a different cost. Bands no longer work, because the cheapest route may use more jumps. Use Dijkstra's algorithm, or a table if hops are short.
  • Only reachability matters. Drop the counter and keep the edge, which is Jump Game.
  • Many queries for different targets. One pass that records the band number of every square answers all of them.

Talking through it

Fictional example

One way to narrate the solution
Candidate
This is a shortest path with every move costing one, so breadth-first search is the natural fit. Squares are nodes and hops are edges.
Candidate
Because hops only go forward and can be shortened, the squares at distance k form one contiguous band. I can track a band with its end index instead of a queue.
Candidate
While scanning a band I keep the farthest square it can reach. When I hit the band's end, I add a jump and that farthest square becomes the new end. It's linear time, constant space, and I return -1 if a band can't extend.

Jump Game is the yes-or-no version and builds the single-edge idea this page extends. Partition Labels uses the same extend-then-close move on a string: keep pushing a boundary, and cut when the scan arrives at it. Interleaving String shows the opposite case, where no greedy rule is safe and a table is required. More are on the coding problems hub.

Natively in your practice sessions

While you prepare on a Mac or a Windows PC, Natively can capture this problem from your screen and help you spot that it is a breadth-first search with contiguous layers. Your mock round is transcribed and saved with notes, so you can go back and check whether you explained the band boundaries before writing the loop. The AI interview assistant page covers the details.

Questions people ask

How do you solve Jump Game II?

Scan the array keeping the end of the current band of squares and the farthest square any of them can reach. When the scan reaches the band's end, add a jump and make the farthest square the new end. Stop once the last square is covered.

Is Jump Game II a BFS problem?

Yes. It is a shortest path where every jump costs one. Because the squares reachable in k jumps form one contiguous band, two indexes replace the queue, giving O(n) time and O(1) space.

Why not always take the longest jump in Jump Game II?

The furthest landing square may have a small hop. The right choice is the square whose own hop reaches furthest, and tracking the band's farthest reach makes that choice automatically.

What if the last index cannot be reached in Jump Game II?

Many versions guarantee it can. If not, detect it when a band closes without extending past its end, and return -1.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP