Hone logo
Hone
Problems

Jump Game II: Minimum Jumps to Reach End

You are given an array of non-negative integers, where each element represents the maximum jump length from that position. Your goal is to reach the last index of the array starting from the first index. This challenge is a classic example of optimizing a path and is crucial for understanding greedy algorithms and dynamic programming concepts.

Problem Description

Given a 0-indexed array of integers nums of length n, where nums[i] represents the maximum jump length from index i. You are initially positioned at nums[0].

Your task is to find the minimum number of jumps required to reach the last index (n-1). You can assume that you can always reach the last index.

Key Requirements:

  • Start at index 0.
  • Reach index n-1.
  • Minimize the total number of jumps taken.

Expected Behavior: The function should return a single integer representing the minimum number of jumps.

Edge Cases:

  • An array with only one element: The number of jumps should be 0.
  • An array where the first element allows you to reach the end in one jump.

Examples

Example 1:

Input: nums = [2,3,1,1,4]
Output: 2
Explanation: 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.

Example 2:

Input: nums = [2,3,0,1,4]
Output: 2
Explanation: 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.

Example 3:

Input: nums = [1,1,1,1]
Output: 3
Explanation: From index 0, jump to index 1. From index 1, jump to index 2. From index 2, jump to index 3.

Constraints

  • 1 <= nums.length <= 10^4
  • 0 <= nums[i] <= 1000
  • It is guaranteed that you can always reach the last index.
  • The solution should aim for an efficient time complexity.

Notes

Consider how you can make the "best" jump at each step to minimize the total number of jumps. Think about the furthest you can reach with each jump. This problem can be solved efficiently using a greedy approach.

Loading editor...
plaintext