45. Jump Game II
Asked at 28Amazon59Microsoft53Google45Bloomberg45Meta37Apple22Meesho57Flipkart52Infosys30Salesforce28Groupon72HashedIn72Zoho70Grab66ServiceNow66PhonePe64eBay64Nutanix60TikTok46Adobe44Atlassian42Snowflake39IBM35DoorDash29Goldman Sachs28tcs27Oracle27Uber22
Problem
You start at index 0, and nums[i] is the maximum jump length from index i. Return the minimum number of jumps to reach the last index (always possible).
Example: [2,3,1,1,4] → 2 (0 → 1 → 4)
Constraints: n ≤ 10⁴.
BFS by "levels": the current jump covers [.., end]; while scanning it, track the farthest next reach. When you hit end, you must jump: jumps += 1, end = farthest.
nums 2 3 1 1 4
[0] jump 1 covers 1..2
[1 2] farthest = 4 -> jump 2 reaches the end
Complexity: O(n).
class Solution:
def jump(self, nums: List[int]) -> int:
jumps = end = far = 0
for i in range(len(nums) - 1):
far = max(far, i + nums[i])
if i == end:
jumps += 1
end = far
return jumps
assert Solution().jump([2, 3, 1, 1, 4]) == 2
assert Solution().jump([2, 3, 0, 1, 4]) == 2
assert Solution().jump([0]) == 0
class Solution {
public int jump(int[] nums) {
int jumps = 0, end = 0, far = 0;
for (int i = 0; i < nums.length - 1; i++) {
far = Math.max(far, i + nums[i]);
if (i == end) { jumps++; end = far; }
}
return jumps;
}
}
func jump(nums []int) int {
jumps, end, far := 0, 0, 0 // BFS by levels: [.., end] is reachable with `jumps` jumps
for i := 0; i < len(nums)-1; i++ {
far = max(far, i+nums[i])
if i == end {
jumps++
end = far
}
}
return jumps
}