Jump Game II - Go Solution

Solving the LeetCode "Jump Game II" Problem in Go

Difficulty: Medium | Tags: Array, Dynamic Programming, Greedy

Introduction

The "Jump Game II" problem requires finding the minimum number of jumps needed to reach the end of an array, where each element represents the maximum jump length from that position. This problem is a classic example of greedy algorithms and dynamic programming.

Problem Analysis

Given a 0-indexed array `nums`, each element `nums[i]` indicates the maximum jump length from index `i`. The goal is to reach the last index (`nums[n-1]`) with the fewest jumps. For example, in `nums = [2,3,1,1,4]`, the optimal path is jumping from index 0 to 1 (1 step), then from index 1 to 4 (3 steps), totaling 2 jumps.

Solution Approach

The optimal solution uses a greedy approach. We track the farthest position reachable in the current jump (`maxReach`) and the end of the current jump (`end`). For each index, we update `maxReach` to the farthest position reachable from the current index. When we reach `end`, we increment the jump count and set `end` to `maxReach`.

Go Implementation


func jump(nums []int) int {
    jumps := 0
    maxReach := 0
    end := 0
    for i := 0; i < len(nums)-1; i++ {
        if i+nums[i] > maxReach {
            maxReach = i + nums[i]
        }
        if i == end {
            jumps++
            end = maxReach
        }
    }
    return jumps
}

Complexity Analysis

Time Complexity: O(n), where `n` is the length of `nums`. We traverse the array once.
Space Complexity: O(1), as we use only a few extra variables.

Testing and Examples

Example 1: `nums = [2,3,1,1,4]` → Output: 2
Example 2: `nums = [2,3,0,1,4]` → Output: 2
Edge Case: `nums = [1]` → Output: 0 (already at the last index).

Best Practices and Tips

1. Use a greedy approach for optimal performance.
2. Ensure the loop runs only up to `len(nums)-1` to avoid unnecessary checks.
3. Test edge cases like single-element arrays or arrays where the first element can reach the end in one jump.