![]() |
VOOZH | about |
Given an array arr[] of non-negative integers, where each element represents the maximum number of steps you can jump forward from that index, determine the minimum number of jumps required to reach the last index starting from the first index. If it is not possible to reach the end, return -1.
Examples:
Input: arr[] = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9]
Output: 3
Explanation: First jump from 1st element to 2nd element with value 3. From here we jump to 5th element with value 9, and from here we will jump to the last.Input: arr []= [1, 4, 3, 2, 6, 7]
Output: 2
Explanation: First we jump from the 1st to 2nd element and then jump to the last element.Input: arr[] = [0, 10, 20]
Output: -1
Explanation: We cannot go anywhere from the 1st element.
Table of Content
Recursively try all possible jumps from each index. From position i, we can jump to any index between i + 1 and i + arr[i], and for each of these, we compute the minimum jumps needed to reach the end. then take the minimum among those and add 1 for the current jump.
Basically minJumps(i) = 1 + min(minJumps(k)) for all valid k reachable from i.
3
For example in array, arr[] = {1, 3, 5, 8, 9, 2, 6,} minJumps(3) will be called two times as arr[3] is reachable from arr[1] and arr[2]. So this problem has both properties (optimal substructure and overlapping subproblems) of Dynamic Programming.
We create an array dp[] of size n, where each element dp[i] stores the minimum steps required to reach end of array from index i. Start from the last index i.e. n-1, and for each index i, compute the minimum steps for subarray i to n-1 and store the result in dp[i].
3
The core idea is to greedily track the farthest reachable index (maxReach). Instead of jumping at every step, keep moving within the current range. Only when you reach the end of that range, take a jump and extend the range to maxReach. This way, each jump covers the maximum possible distance, ensuring the minimum number of jumps.
For implementation, these variables are utilized during the iterative process:
In each iteration, update maxReach as max(maxReach, i + arr[i]). When currentReach is reached, increase jumps and set currentReach to maxReach. If at any time i equals currentReach and maxReach is also equal to currentReach, it's impossible to reach the end, thus return -1.
3