Jump Game II

Minimum jumps to reach the last index — BFS-style "current reach" frontier.

Medium
Time O(n) Space O(1)
LeetCode
3 min read
greedy array

Problem#

Same as Jump Game I but return the minimum number of jumps to reach the last index. Reachability is guaranteed.

Examples#

  • [2,3,1,1,4]2
  • [2,3,0,1,4]2

Constraints#

  • 1 <= n <= 10^4.

Approach#

Implicit BFS: maintain currentEnd (end of “this jump”) and farthest (max reach from anywhere in the current segment). When you reach currentEnd, commit a jump and set currentEnd = farthest.

Solution#

Jump Game II
class Solution {
public:
int jump(vector<int>& nums) {
int jumps = 0, currentEnd = 0, farthest = 0;
for (int i = 0; i < (int)nums.size() - 1; ++i) {
farthest = max(farthest, i + nums[i]);
if (i == currentEnd) {
++jumps;
currentEnd = farthest;
}
}
return jumps;
}
};

Editorial#

Conceptually a BFS over “how many jumps to reach index i?”. The trick is that within a “jump level” (positions reachable in j jumps), we know the next level’s frontier without explicitly enqueueing — it’s just the max-reach across the current level. Loop ends at n - 2 because reaching the last index doesn’t require an additional outgoing jump.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.