AlgoInsight

DSA problem

Jump Game II

MediumGreedyPattern: Greedytop75FreeAmazonMicrosoftGoogleMetaApple

You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0]. Each element nums[i] represents the maximum length of a forward jump from index i, so you can jump to any index i + j where 1 <= j <= nums[i] and i + j < n. Return the minimum number of jumps to reach n - 1. The test cases are generated such that you can always reach the last index.

A classic dynamic-programming solution computes the minimum jumps to each index in O(n^2) time. The greedy reformulation reduces this to O(n) by realizing the problem is implicitly a Breadth-First Search on the array, where each "level" is the set of indices reachable in the same number of jumps.

Maintain three variables: jumps (the answer so far), currentEnd (the rightmost index in the current BFS level), and farthest (the farthest index any position in the current level can reach). As you scan, farthest = max(farthest, i + nums[i]). When the iteration index i reaches currentEnd, you have exhausted the current level: increment jumps and promote currentEnd to farthest, opening the next BFS level.

The algorithm walks indices 0 through n - 2 (you do not need to jump from the last index — you have already arrived). This is provably optimal because every position in the current level shares the same jump count, so taking the maximum reach across them gives the maximum reach of the next level. Time complexity is O(n) and space is O(1).

Examples

Example 1
Input: nums = [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2
Input: nums = [2,3,0,1,4]
Output: 2
Explanation: From index 0 jump to index 1 (jumps = 1, level reach = 4). From index 1 we can reach index 4, completing the trip in 2 jumps.
Example 3
Input: nums = [1,2,1,1,1]
Output: 3
Explanation: Jump 1 → 1 → 3 → 4, three jumps total. The greedy BFS tracks the boundary index at each jump.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

greedyarraydynamic-programming

Browse all DSA problems