Jump Game II - Problem

Imagine you're playing a platformer game where you need to reach the end of a level in the minimum number of jumps! ๐ŸŽฎ

You start at position 0 of an array nums with n elements. Each element nums[i] represents the maximum jump distance you can make from that position. From index i, you can jump to any index j where i < j โ‰ค i + nums[i].

Your mission: Find the minimum number of jumps needed to reach the last index (n-1).

Example: If nums = [2,3,1,1,4], you can jump from index 0 to index 1 (jump distance 1), then from index 1 to index 4 (jump distance 3). That's just 2 jumps to reach the end!

โšก Good news: The test cases guarantee that you can always reach the end, so focus on finding the optimal path!

Input & Output

example_1.py โ€” Python
$ Input: nums = [2,3,1,1,4]
โ€บ Output: 2
๐Ÿ’ก Note: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. Path: 0 โ†’ 1 โ†’ 4
example_2.py โ€” Python
$ Input: nums = [2,3,0,1,4]
โ€บ Output: 2
๐Ÿ’ก Note: Still need 2 jumps. From index 0, jump 2 steps to index 2, then jump 2 steps to reach index 4 (the last index). Path: 0 โ†’ 2 โ†’ 4
example_3.py โ€” Python
$ Input: nums = [1,1,1,1]
โ€บ Output: 3
๐Ÿ’ก Note: Each element only allows 1 step jumps, so we need 3 jumps to go from index 0 to index 3. Path: 0 โ†’ 1 โ†’ 2 โ†’ 3

Visualization

Tap to expand
๐Ÿ๏ธStart๐Ÿ๏ธ๐Ÿ๏ธ๐Ÿ๏ธ๐Ÿ’ŽTreasureJump Level 1Jump Level 2Greedy Strategy: Always Choose Maximum Range!Track farthest reachable position at each jump level
Understanding the Visualization
1
Level 0: Starting Island
Begin at island 0, can reach islands within range of current launcher
2
Level 1: First Jump
After 1 jump, determine all islands reachable. Track the farthest possible.
3
Level 2: Second Jump
When we must make a second jump, update our reachable range again
4
Optimal Path Found
Continue until treasure island is within reach
Key Takeaway
๐ŸŽฏ Key Insight: Instead of exploring every possible jump path, the greedy approach tracks reachable boundaries level by level, guaranteeing the minimum number of jumps!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(nยฒ)

In worst case, we might visit each position multiple times, and for each position we try up to n jumps

n
2n
โš  Quadratic Growth
Space Complexity
O(n)

Space for memoization array and recursion stack depth

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 104
  • 0 โ‰ค nums[i] โ‰ค 1000
  • It's guaranteed that you can reach nums[n - 1]
Asked in
Google 67 Amazon 54 Meta 43 Microsoft 38 Apple 29
42.5K Views
High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen