Given an array of integers where each element represents the max number of steps that can be made forward from that element. Write a function to return the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then we cannot move through that element. If we can’t reach the end, return -1.
Prerequisite: Minimum number of jumps to reach end | Set-1 ( O(n2) solution)
Examples:Â
Input: arr[] = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9}
Output: 3 (1-> 3 -> 8 -> 9)
Explanation: Jump from 1st element to 2nd element as there is only 1 step, now there are three options 5, 8 or 9. If 8 or 9 is chosen then the end node 9 can be reached. So 3 jumps are made.
Input : arr[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
Output: 10
Explanation: In every step a jump is needed so the count of jumps is 10.
Minimum number of jumps to reach end using Greedy approach:
The idea is to use greedy approach to find the minimum jumps needed to reach the end of an array by iterating through the array while maintaining the maximum reachable index and the remaining steps in the current jump and updating these values based on the array elements.
Follow the steps below to solve the problem:
- Initialize the variables maxReach, step, and jump to keep track of the maximum reachable index, the remaining steps at the current position, and the number of jumps taken, respectively.
- Traverse the array and update the maximum reachable index based on the sum of the current index and its corresponding array value. This helps determine how far the current jump can take us.
- If the remaining steps for the current jump are exhausted, a new jump is initiated.
- If the current index surpasses the maximum reachable index, indicating no further progress, -1 is returned meaning no solution is found.
Below is the implementation of above approach:
C++
// C++ program to count Minimum number// of jumps to reach end#include <bits/stdc++.h>using namespace std;Â
int max(int x, int y){Â Â Â Â return (x > y) ? x : y;}Â
// Returns minimum number of jumps// to reach arr[n-1] from arr[0]int minJumps(int arr[], int n){Â
    // The number of jumps needed to    // reach the starting index is 0    if (n <= 1)        return 0;             //If value of first index guarantees       //only 1 jump is needed, return 1      if (arr[0] >= n-1)          return 1;Â
    // Return -1 if not possible to jump    if (arr[0] == 0)        return -1;Â
    // initialization    // stores all time the maximal    // reachable index in the array.    int maxReach = arr[0];Â
    // stores the number of steps    // we can still take    int step = arr[0];Â
    // stores the number of jumps    // necessary to reacach that maximal    // reachable position.    int jump = 1;Â
    // Start traversing array    int i = 1;    for (i = 1; i < n; i++) {        // Check if we have reached the end of the array        if (i == n - 1)            return jump;                //Check if value at current index guarantees jump to end          if (arr[i] >= (n-1) - i)              return jump + 1;Â
        // updating maxReach        maxReach = max(maxReach, i + arr[i]);Â
        // we use a step to get to the current index        step--;Â
        // If no further steps left        if (step == 0) {            // we must have used a jump            jump++;Â
            // Check if the current index/position or lesser index            // is the maximum reach point from the previous indexes            if (i >= maxReach)                return -1;Â
            // re-initialize the steps to the amount            // of steps to reach maxReach from position i.            step = maxReach - i;        }    }Â
    return -1;}Â
// Driver program to test above functionint main(){Â Â Â Â int arr[] = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 };Â Â Â Â int size = sizeof(arr) / sizeof(int);Â
    // Calling the minJumps function    cout << ("Minimum number of jumps to reach end is %d ",             minJumps(arr, size));    return 0;}// This code is contributed by// Shashank_Sharma |
C
// C program to count Minimum number// of jumps to reach end#include <stdio.h>Â
int max(int x, int y) { return (x > y) ? x : y; }Â
// Returns minimum number of jumps// to reach arr[n-1] from arr[0]int minJumps(int arr[], int n){Â
    // The number of jumps needed to    // reach the starting index is 0    if (n <= 1)        return 0;         //If value of first index guarantees       //only 1 jump is needed, return 1      if (arr[0] >= n-1)          return 1;Â
    // Return -1 if not possible to jump    if (arr[0] == 0)        return -1;Â
    // initialization    // stores all time the maximal    // reachable index in the array.    int maxReach = arr[0];Â
    // stores the number of steps    // we can still take    int step = arr[0];Â
    // stores the number of jumps    // necessary to reach that maximal    // reachable position.    int jump = 1;Â
    // Start traversing array    int i = 1;    for (i = 1; i < n; i++) {        // Check if we have reached the end of the array        if (i == n - 1)            return jump;                   //Check if value at current index guarantees jump to end          if (arr[i] >= (n-1) - i)              return jump + 1;                   // updating maxReach        maxReach = max(maxReach, i + arr[i]);Â
        // we use a step to get to the current index        step--;Â
        // If no further steps left        if (step == 0) {            // we must have used a jump            jump++;Â
            // Check if the current index/position or lesser index            // is the maximum reach point from the previous indexes            if (i >= maxReach)                return -1;Â
            // re-initialize the steps to the amount            // of steps to reach maxReach from position i.            step = maxReach - i;        }    }    return -1;}Â
// Driver program to test above functionint main(){Â Â Â Â int arr[] = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 };Â Â Â Â int size = sizeof(arr) / sizeof(int);Â
    // Calling the minJumps function    printf(        "Minimum number of jumps to reach end is %d ",        minJumps(arr, size));    return 0;}// This code is contributed by Abhishek Kumar Singh |
Java
// Java program to count Minimum number// of jumps to reach endÂ
class Test {    static int minJumps(int arr[])    {        if (arr.length <= 1)            return 0;                 //If value of first index guarantees           //only 1 jump is needed, return 1        if (arr[0] >= arr.length-1)            return 1;Â
        // Return -1 if not possible to jump        if (arr[0] == 0)            return -1;Â
        // initialization        int maxReach = arr[0];        int step = arr[0];        int jump = 1;Â
        // Start traversing array        for (int i = 1; i < arr.length; i++) {            // Check if we have reached // the end of the array            if (i == arr.length - 1)                return jump;                     //Check if value at current index guarantees jump to end            if (arr[i] >= (arr.length-1) - i)                return jump + 1;Â
            // updating maxReach            maxReach = Math.max(maxReach, i + arr[i]);Â
            // we use a step to get to the current index            step--;Â
            // If no further steps left            if (step == 0) {                // we must have used a jump                jump++;Â
                // Check if the current // index/position or lesser index                // is the maximum reach point // from the previous indexes                if (i >= maxReach)                    return -1;Â
                // re-initialize the steps to the amount                // of steps to reach maxReach from position i.                step = maxReach - i;            }        }Â
        return -1;    }Â
    // Driver method to test the above function    public static void main(String[] args)    {        int arr[] = new int[] { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 };Â
        // calling minJumps method        System.out.println(minJumps(arr));    }} |
Python3
# python program to count Minimum number# of jumps to reach end  # Returns minimum number of jumps to reach arr[n-1] from arr[0]def minJumps(arr, n):  # The number of jumps needed to reach the starting index is 0  if (n <= 1):    return 0     #If value of first index guarantees only 1 jump is needed, return 1  if (arr[0] >= n-1):      return 1    # Return -1 if not possible to jump  if (arr[0] == 0):    return -1    # initialization  # stores all time the maximal reachable index in the array  maxReach = arr[0]   # stores the amount of steps we can still take  step = arr[0]  # stores the amount of jumps necessary to reach that maximal reachable position  jump = 1    # Start traversing array    for i in range(1, n):    # Check if we have reached the end of the array    if (i == n-1):      return jump         #Check if value at current index guarantees jump to end    if (arr[i] >= (n-1) - i):        return jump + 1      # updating maxReach    maxReach = max(maxReach, i + arr[i])      # we use a step to get to the current index    step -= 1;      # If no further steps left    if (step == 0):      # we must have used a jump      jump += 1             # Check if the current index / position or lesser index      # is the maximum reach point from the previous indexes      if(i >= maxReach):        return -1        # re-initialize the steps to the amount      # of steps to reach maxReach from position i.      step = maxReach - i;  return -1  Â
# Driver program to test above functionarr = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9]size = len(arr)Â Â # Calling the minJumps functionprint("Minimum number of jumps to reach end is % d " % minJumps(arr, size))Â
# This code is contributed by Aditi Sharma |
C#
// C# program to count Minimum// number of jumps to reach endusing System;Â
class GFG {Â Â Â Â static int minJumps(int[] arr)Â Â Â Â {Â Â Â Â Â Â Â Â if (arr.Length <= 1)Â Â Â Â Â Â Â Â Â Â Â Â return 0;Â
        // Return -1 if not        // possible to jump        if (arr[0] == 0)            return -1;Â
        // initialization        int maxReach = arr[0];        int step = arr[0];        int jump = 1;Â
        // Start traversing array        for (int i = 1; i < arr.Length; i++) {            // Check if we have reached            // the end of the array            if (i == arr.Length - 1)                return jump;Â
            // updating maxReach            maxReach = Math.Max(maxReach, i + arr[i]);Â
            // we use a step to get            // to the current index            step--;Â
            // If no further steps left            if (step == 0) {                // we must have used a jump                jump++;Â
                // Check if the current index/position                // or lesser index is the maximum reach                // point from the previous indexes                if (i >= maxReach)                    return -1;Â
                // re-initialize the steps to                // the amount of steps to reach                // maxReach from position i.                step = maxReach - i;            }        }Â
        return -1;    }Â
    // Driver Code    public static void Main()    {        int[] arr = new int[] { 1, 3, 5, 8, 9, 2,                                6, 7, 6, 8, 9 };Â
        // calling minJumps method        Console.Write(minJumps(arr));    }}Â
// This code is contributed// by nitin mittal |
Javascript
<script>     // Javascript program to count Minimum number  Â
// Returns minimum number of jumpsÂ
// to reach arr[n-1] from arr[0]Â
function minJumps(arr,n)Â
{Â
  Â
    // The number of jumps needed toÂ
    // reach the starting index is 0Â
    if (n <= 1)Â
        return 0;Â
  Â
    // Return -1 if not possible to jumpÂ
    if (arr[0] == 0)Â
        return -1;Â
  Â
    // initializationÂ
    // stores all time the maximalÂ
    // reachable index in the array.Â
    let maxReach = arr[0];Â
  Â
    // stores the number of stepsÂ
    // we can still takeÂ
    let step = arr[0];Â
  Â
    // stores the number of jumpsÂ
    // necessary to reach that maximalÂ
    // reachable position.Â
    let jump = 1;Â
  Â
    // Start traversing arrayÂ
    let i = 1;Â
    for (i = 1; i < n; i++) {Â
        // Check if we have reached the end of the arrayÂ
        if (i == n - 1)Â
            return jump;Â
  Â
        // updating maxReachÂ
        maxReach =Math.max(maxReach, i + arr[i]);Â
Â
Â
        // we use a step to get to the current indexÂ
        step--;Â
  Â
        // If no further steps leftÂ
        if (step == 0) {Â
            // we must have used a jumpÂ
            jump++;Â
  Â
            // Check if the current index/position or lesser indexÂ
            // is the maximum reach point from the previous indexesÂ
            if (i >= maxReach)Â
                return -1;Â
  Â
            // re-initialize the steps to the amountÂ
            // of steps to reach maxReach from position i.Â
            step = maxReach - i;Â
        }Â
    }Â
  Â
    return -1;Â
}Â
  Â
// Driver program to test above functionÂ
Â
Â
    var arr = [ 1, 3, 5, 8, 9, 2, 6, 7, 6, 8,9 ];Â
    let size = arr.length;Â
  Â
    // Calling the minJumps functionÂ
    document.write("Minimum number of jumps to reach end is "+Â
             minJumps(arr, size));Â
     Â
// This code is contributed byÂ
// Potta LokeshÂ
     Â
</script> |
PHP
<?php // PHP program to count Minimum number// of jumps to reach end  // Returns minimum number of jumps to reach arr[n-1] from arr[0]function minJumps(&$arr, $n){          // The number of jumps needed to reach the starting index is 0    if ($n <= 1)        return 0;      // Return -1 if not possible to jump    if ($arr[0] == 0)        return -1;      // initialization    // stores all time the maximal reachable index in the array.    $maxReach = $arr[0]; Â
    // stores the number of steps we can still take     $step = $arr[0]; Â
    //stores the number of jumps necessary to reach that    // maximal reachable position.        $jump =1;Â
    // Start traversing array    $i=1;    for ($i = 1; $i < $n; $i++)    {        // Check if we have reached the end of the array        if ($i == $n-1)            return $jump;          // updating maxReach        $maxReach = max($maxReach, $i+$arr[$i]);          // we use a step to get to the current index        $step--;          // If no further steps left        if ($step == 0)        {            // we must have used a jump            $jump++;              // Check if the current index/position or lesser index            // is the maximum reach point from the previous indexes            if($i >= $maxReach)                return -1;              // re-initialize the steps to the amount            // of steps to reach maxReach from position i.            $step = $maxReach - $i;        }    }      return -1;}  // Driver program to test above functionÂ
$arr=array(1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9);$size = sizeof($arr)/sizeof($arr[0]);Â Â // Calling the minJumps functionecho "Minimum number of jumps to reach end is "Â Â Â Â Â . minJumps($arr, $size);return 0;// This code is contributed by Ita_c.?> |
3
Complexity Analysis:Â Â
- Time complexity: O(n), Only one traversal of the array is needed.
- Auxiliary Space: O(1), There is no space required.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
