← Back to All Algorithms

Medium Interview Frequency: ⭐⭐⭐⭐

Jump Game II

Return the minimum number of jumps needed to reach the last index, where nums[i] is max jump length from index i.

Greedy Range Expansion

📚 Table of Contents

  1. Problem Statement
  2. Real-World Analogy
  3. Key Insights
  4. Solution Approaches
  5. Step-by-Step Walkthrough
  6. Complexity Analysis
  7. Edge Cases
  8. Test Cases
  9. Interview Tips
  10. Key Takeaways

📋 Problem Statement

Input guarantees that the end is reachable.

Example 1:
Input: [2,3,1,1,4]
Output: 2
Example 2:
Input: [2,3,0,1,4]
Output: 2

🎯 Real-World Analogy

Level-by-Level Network Coverage

Treat each jump count as a layer. Within current layer [start,end], compute farthest index reachable by one more jump. Then move to next layer.

💡 Key Insights

💻 Solution Approaches

Approach 1: DP (Too Slow)

Time: O(N²) | Space: O(N)

Approach 2: Greedy Layer Sweep (Recommended)

Time: O(N) | Space: O(1)

Python Implementation

from typing import List def jump(nums: List[int]) -> int: jumps = 0 current_end = 0 farthest = 0 for i in range(len(nums) - 1): farthest = max(farthest, i + nums[i]) if i == current_end: jumps += 1 current_end = farthest return jumps

JavaScript Implementation

function jump(nums) { let jumps = 0; let currentEnd = 0; let farthest = 0; for (let i = 0; i < nums.length - 1; i++) { farthest = Math.max(farthest, i + nums[i]); if (i === currentEnd) { jumps += 1; currentEnd = farthest; } } return jumps; }

🔍 Step-by-Step Walkthrough

Trace [2,3,1,1,4]:

i=0 -> farthest=2, boundary hit -> jumps=1, currentEnd=2
i=1 -> farthest=4
i=2 -> farthest=4, boundary hit -> jumps=2, currentEnd=4
Reached/passed last index in 2 jumps.

⚡ Complexity Analysis

Time: O(N), one pass through indices.

Space: O(1), only counters and boundaries.

🔧 Edge Cases

🧪 Test Cases

Python

def test_jump(): assert jump([2,3,1,1,4]) == 2 assert jump([2,3,0,1,4]) == 2 assert jump([0]) == 0 assert jump([1,1,1,1]) == 3 print("✅ all tests passed")

JavaScript

function testJump() { console.assert(jump([2,3,1,1,4]) === 2, "test 1"); console.assert(jump([2,3,0,1,4]) === 2, "test 2"); console.assert(jump([0]) === 0, "test 3"); console.log("✅ all tests passed"); }

💼 Interview Tips

🎓 Key Takeaways

← Back to All Algorithms