The Wayback Machine - https://web.archive.org/web/20250102130620/https://www.geeksforgeeks.org/minimum-number-of-jumps-to-reach-end-of-a-given-array/
Open In App

Jump Game – Minimum Jumps to Reach End

Last Updated : 25 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array arr[] of non-negative integers. Each array element represents the maximum length of the jumps that can be made forward from that element. This means if arr[i] = x, then we can jump any distance y such that y ≤ x. Find 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.

Note:  Return -1 if we can’t reach the end of the array.

Examples: 

Input: arr[] = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9]
Output: 3 (1-> 3 -> 9 -> 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.

Using Recursion – O(n^n) Time and O(n) Space

Start from the first element and recursively call for all the elements reachable from the first element. The minimum number of jumps to reach end from first can be calculated using the minimum value from the recursive calls. 

minJumps(start) = 1 + Min(minJumps(k)) for all k reachable from start.

C++
// c++ program to find the minimum number
// of jumps to reach the end of the array
#include <bits/stdc++.h>
using namespace std;

int minJumpsRecur(int i, vector<int> &arr) {
    
    // Return 0 when last element is reached.
    if (i >= arr.size()-1)
        return 0;

    // Traverse through all the points
    // reachable from arr[i].
    // Recursively, get the minimum number
    // of jumps needed to reach array end from
    // these points.
    int ans = INT_MAX;
    for (int j=i+1; j<=i+arr[i]; j++) {
        int val = minJumpsRecur(j, arr);
        if (val != INT_MAX)
            ans = min(ans, 1+val);
    }

    return ans;
}

// Function to return the minimum number
// of jumps to reach arr[h] from arr[l]
int minJumps(vector<int>& arr) {

    int ans =  minJumpsRecur(0, arr);
    
    // If end cannot be reached.
    if (ans == INT_MAX) 
        return -1;
        
    return ans;
}

int main() {
    vector<int> arr = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 };
    cout << minJumps(arr);
    return 0;
}
Java
// Java program to find the minimum number
// of jumps to reach the end of the array

import java.util.Arrays;

class GfG {

    static int minJumpsRecur(int i, int[] arr) {
        
        // Return 0 when last element is reached.
        if (i >= arr.length - 1)
            return 0;

        // Traverse through all the points
        // reachable from arr[i].
        // Recursively, get the minimum number
        // of jumps needed to reach array end from
        // these points.
        int ans = Integer.MAX_VALUE;
        for (int j = i + 1; j <= i + arr[i]; j++) {
            int val = minJumpsRecur(j, arr);
            if (val != Integer.MAX_VALUE)
                ans = Math.min(ans, 1 + val);
        }

        return ans;
    }

    static int minJumps(int[] arr) {

        int ans = minJumpsRecur(0, arr);
        
        // If end cannot be reached.
        if (ans == Integer.MAX_VALUE) 
            return -1;
            
        return ans;
    }

    public static void main(String[] args) {
        int[] arr = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 };
        System.out.println(minJumps(arr));
    }
}
Python
# Python program to find the minimum number
# of jumps to reach the end of the array

import sys

def minJumpsRecur(i, arr):
    
    # Return 0 when last element is reached.
    if i >= len(arr) - 1:
        return 0

    # Traverse through all the points
    # reachable from arr[i].
    # Recursively, get the minimum number
    # of jumps needed to reach array end from
    # these points.
    ans = sys.maxsize
    for j in range(i + 1, i + arr[i] + 1):
        val = minJumpsRecur(j, arr)
        if val != sys.maxsize:
            ans = min(ans, 1 + val)

    return ans

def minJumps(arr):
    ans = minJumpsRecur(0, arr)
    
    # If end cannot be reached.
    if ans == sys.maxsize:
        return -1
        
    return ans

if __name__ == "__main__":
    arr = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9]
    print(minJumps(arr))
C#
// C# program to find the minimum number
// of jumps to reach the end of the array

using System;

class GfG {

    static int minJumpsRecur(int i, int[] arr) {
        
        // Return 0 when last element is reached.
        if (i >= arr.Length - 1)
            return 0;

        // Traverse through all the points
        // reachable from arr[i].
        // Recursively, get the minimum number
        // of jumps needed to reach array end from
        // these points.
        int ans = int.MaxValue;
        for (int j = i + 1; j <= i + arr[i]; j++) {
            int val = minJumpsRecur(j, arr);
            if (val != int.MaxValue)
                ans = Math.Min(ans, 1 + val);
        }

        return ans;
    }

    static int minJumps(int[] arr) {

        int ans = minJumpsRecur(0, arr);
        
        // If end cannot be reached.
        if (ans == int.MaxValue) 
            return -1;
            
        return ans;
    }

    static void Main() {
        int[] arr = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 };
        Console.WriteLine(minJumps(arr));
    }
}
JavaScript
// JavaScript program to find the minimum number
// of jumps to reach the end of the array

function minJumpsRecur(i, arr) {
    
    // Return 0 when last element is reached.
    if (i >= arr.length - 1)
        return 0;

    // Traverse through all the points
    // reachable from arr[i].
    // Recursively, get the minimum number
    // of jumps needed to reach array end from
    // these points.
    let ans = Infinity;
    for (let j = i + 1; j <= i + arr[i]; j++) {
        let val = minJumpsRecur(j, arr);
        if (val != Infinity)
            ans = Math.min(ans, 1 + val);
    }

    return ans;
}

function minJumps(arr) {
    let ans = minJumpsRecur(0, arr);
    
    // If end cannot be reached.
    if (ans == Infinity) 
        return -1;
        
    return ans;
}

let arr = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9];
console.log(minJumps(arr));

Output
3

Using Top-Down DP (Memoization) – O(n^2) Time and O(n) Space

If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming:

1. Optimal Substructure: Number of ways to reach the array end from current index i, i.e., minJumps(i), depends on the optimal solutions of the subproblems minJumps(i+1), minJumps(i+2), …., minJumps(i+arr[i]). By finding the minimum jumps in these optimal substructures, we can efficiently calculate the total number of jumps to reach the end.

2. Overlapping Subproblems: While applying a recursive approach in this problem, we notice that certain subproblems are computed multiple times. So we can compute the value for a given index and store it in an array, so that if this index is again called, we can simply return the stored value.

Follow the below steps to implement the idea:

  • Create memo[] such that memo[i] indicates the minimum number of jumps needed to reach memo[n-1] from memo[i] to store previously solved subproblems.
  • During the recursion call, if the same state is called more than once, then we can directly return the answer stored for that state instead of calculating again.
  • Otherwise, In each recursive call get all the reachable nodes from that index.
    • For each of the index call the recursive function.
    • Find the minimum number of jumps to reach the end from current index.
C++
// c++ program to find the minimum number
// of jumps to reach the end of the array
#include <bits/stdc++.h>
using namespace std;

int minJumpsRecur(int i, vector<int> &arr, vector<int> &memo) {
    
    // Return 0 when last element is reached.
    if (i == arr.size()-1)
        return 0;
        
    // If value for current index is memoized,
    // then return it.
    if (memo[i] != -1) return memo[i];

    // Traverse through all the points
    // reachable from arr[i].
    // Recursively, get the minimum number
    // of jumps needed to reach array end from
    // these points.
    int ans = INT_MAX;
    for (int j=i+1; j<=i+arr[i] && j<arr.size(); j++) {
        int val = minJumpsRecur(j, arr, memo);
        if (val != INT_MAX)
            ans = min(ans, 1+val);
    }
    
    // Memoize the value and 
    // return it.
    return memo[i] = ans;
}

// Function to return the minimum number
// of jumps to reach arr[h] from arr[l]
int minJumps(vector<int>& arr) {
    
    // array to memoize values
    vector<int> memo(arr.size(), -1);
    
    int ans =  minJumpsRecur(0, arr, memo);
    
    // If end cannot be reached.
    if (ans == INT_MAX) 
        return -1;
        
    return ans;
}

int main() {
    vector<int> arr = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 };
    cout << minJumps(arr);
    return 0;
}
Java
// Java program to find the minimum number
// of jumps to reach the end of the array

class GfG {

    static int minJumpsRecur(int i, int[] arr, int[] memo) {

        // Return 0 when last element is reached.
        if (i == arr.length - 1)
            return 0;

        // If value for current index is memoized,
        // then return it.
        if (memo[i] != -1) return memo[i];

        // Traverse through all the points
        // reachable from arr[i].
        // Recursively, get the minimum number
        // of jumps needed to reach array end from
        // these points.
        int ans = Integer.MAX_VALUE;
        for (int j = i + 1; j <= i + arr[i] && j < arr.length; j++) {
            int val = minJumpsRecur(j, arr, memo);
            if (val != Integer.MAX_VALUE)
                ans = Math.min(ans, 1 + val);
        }

        // Memoize the value and 
        // return it.
        return memo[i] = ans;
    }

    // Function to return the minimum number
    // of jumps to reach arr[h] from arr[l]
    static int minJumps(int[] arr) {

        // array to memoize values
        int[] memo = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            memo[i] = -1;
        }

        int ans = minJumpsRecur(0, arr, memo);

        // If end cannot be reached.
        if (ans == Integer.MAX_VALUE)
            return -1;

        return ans;
    }

    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9};
        System.out.println(minJumps(arr));
    }
}
Python
# Python program to find the minimum number
# of jumps to reach the end of the array

def minJumpsRecur(i, arr, memo):

    # Return 0 when last element is reached.
    if i == len(arr) - 1:
        return 0

    # If value for current index is memoized,
    # then return it.
    if memo[i] != -1:
        return memo[i]

    # Traverse through all the points
    # reachable from arr[i].
    # Recursively, get the minimum number
    # of jumps needed to reach array end from
    # these points.
    ans = float('inf')
    for j in range(i + 1, min(i + arr[i] + 1, len(arr))):
        val = minJumpsRecur(j, arr, memo)
        if val != float('inf'):
            ans = min(ans, 1 + val)

    # Memoize the value and 
    # return it.
    memo[i] = ans
    return ans

# Function to return the minimum number
# of jumps to reach arr[h] from arr[l]
def minJumps(arr):

    # array to memoize values
    memo = [-1] * len(arr)

    ans = minJumpsRecur(0, arr, memo)

    # If end cannot be reached.
    if ans == float('inf'):
        return -1

    return ans

if __name__ == "__main__":
    arr = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9]
    print(minJumps(arr))
C#
// C# program to find the minimum number
// of jumps to reach the end of the array

using System;

class GfG {

    static int minJumpsRecur(int i, int[] arr, int[] memo) {

        // Return 0 when last element is reached.
        if (i == arr.Length - 1)
            return 0;

        // If value for current index is memoized,
        // then return it.
        if (memo[i] != -1) return memo[i];

        // Traverse through all the points
        // reachable from arr[i].
        // Recursively, get the minimum number
        // of jumps needed to reach array end from
        // these points.
        int ans = int.MaxValue;
        for (int j = i + 1; j <= i + arr[i] && j < arr.Length; j++) {
            int val = minJumpsRecur(j, arr, memo);
            if (val != int.MaxValue)
                ans = Math.Min(ans, 1 + val);
        }

        // Memoize the value and 
        // return it.
        return memo[i] = ans;
    }

    // Function to return the minimum number
    // of jumps to reach arr[h] from arr[l]
    static int minJumps(int[] arr) {

        // array to memoize values
        int[] memo = new int[arr.Length];
        for (int i = 0; i < arr.Length; i++) {
            memo[i] = -1;
        }

        int ans = minJumpsRecur(0, arr, memo);

        // If end cannot be reached.
        if (ans == int.MaxValue)
            return -1;

        return ans;
    }

    static void Main(string[] args) {
        int[] arr = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9};
        Console.WriteLine(minJumps(arr));
    }
}
JavaScript
// JavaScript program to find the minimum number
// of jumps to reach the end of the array

function minJumpsRecur(i, arr, memo) {

    // Return 0 when last element is reached.
    if (i === arr.length - 1)
        return 0;

    // If value for current index is memoized,
    // then return it.
    if (memo[i] !== -1) return memo[i];

    // Traverse through all the points
    // reachable from arr[i].
    // Recursively, get the minimum number
    // of jumps needed to reach array end from
    // these points.
    let ans = Infinity;
    for (let j = i + 1; j <= i + arr[i] && j < arr.length; j++) {
        let val = minJumpsRecur(j, arr, memo);
        if (val !== Infinity)
            ans = Math.min(ans, 1 + val);
    }

    // Memoize the value and 
    // return it.
    memo[i] = ans;
    return ans;
}

// Function to return the minimum number
// of jumps to reach arr[h] from arr[l]
function minJumps(arr) {

    // array to memoize values
    let memo = new Array(arr.length).fill(-1);

    let ans = minJumpsRecur(0, arr, memo);

    // If end cannot be reached.
    if (ans === Infinity)
        return -1;

    return ans;
}

let arr = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9];
console.log(minJumps(arr));

Output
3

Using Bottom-Up DP (Tabulation) – O(n^2) Time and O(n) Space

The idea is to create a 1D array of size n. Set dp[n-1] to 0. Then iterate from i = n-2 to i = 0, and find the value of dp[i]. Return value of dp[0].

C++
// c++ program to find the minimum number
// of jumps to reach the end of the array
#include <bits/stdc++.h>
using namespace std;

// Function to return the minimum number
// of jumps to reach arr end.
int minJumps(vector<int> &arr) {
    int n = arr.size();

    // array to memoize values
    vector<int> dp(n, INT_MAX);
    dp[n - 1] = 0;

    for (int i = n - 2; i >= 0; i--) {
        for (int j = i + 1; j <= i + arr[i] && j < n; j++) {
            if (dp[j] != INT_MAX) {
                dp[i] = min(dp[i], 1 + dp[j]);
            }
        }
    }

    // If end cannot be reached.
    if (dp[0] == INT_MAX)
        return -1;

    return dp[0];
}

int main() {
  
    vector<int> arr = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9};
    cout << minJumps(arr);
    return 0;
}
Java
// Java program to find the minimum number
// of jumps to reach the end of the array
import java.util.Arrays;

class GfG {

    // Function to return the minimum number
    // of jumps to reach arr end.
    static int minJumps(int[] arr) {
        int n = arr.length;

        // array to memoize values
        int[] dp = new int[n];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[n - 1] = 0;

        for (int i = n - 2; i >= 0; i--) {
            for (int j = i + 1; j <= i + arr[i] && j < n; j++) {
                if (dp[j] != Integer.MAX_VALUE) {
                    dp[i] = Math.min(dp[i], 1 + dp[j]);
                }
            }
        }

        // If end cannot be reached.
        if (dp[0] == Integer.MAX_VALUE)
            return -1;

        return dp[0];
    }

    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9};
        System.out.println(minJumps(arr));
    }
}
Python
# Python program to find the minimum number
# of jumps to reach the end of the array

def minJumps(arr):
    n = len(arr)

    # array to memoize values
    dp = [float('inf')] * n
    dp[n - 1] = 0

    for i in range(n - 2, -1, -1):
        for j in range(i + 1, min(i + arr[i] + 1, n)):
            if dp[j] != float('inf'):
                dp[i] = min(dp[i], 1 + dp[j])

    # If end cannot be reached.
    if dp[0] == float('inf'):
        return -1

    return dp[0]

if __name__ == "__main__":
    arr = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9]
    print(minJumps(arr))
C#
// C# program to find the minimum number
// of jumps to reach the end of the array

using System;

class GfG {

    // Function to return the minimum number
    // of jumps to reach arr end.
    static int minJumps(int[] arr) {
        int n = arr.Length;

        // array to memoize values
        int[] dp = new int[n];
        Array.Fill(dp, int.MaxValue);
        dp[n - 1] = 0;

        for (int i = n - 2; i >= 0; i--) {
            for (int j = i + 1; j <= i + arr[i] && j < n; j++) {
                if (dp[j] != int.MaxValue) {
                    dp[i] = Math.Min(dp[i], 1 + dp[j]);
                }
            }
        }

        // If end cannot be reached.
        if (dp[0] == int.MaxValue)
            return -1;

        return dp[0];
    }

    static void Main(string[] args) {
        int[] arr = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9};
        Console.WriteLine(minJumps(arr));
    }
}
JavaScript
// JavaScript program to find the minimum number
// of jumps to reach the end of the array

function minJumps(arr) {
    let n = arr.length;

    // array to memoize values
    let dp = new Array(n).fill(Infinity);
    dp[n - 1] = 0;

    for (let i = n - 2; i >= 0; i--) {
        for (let j = i + 1; j <= i + arr[i] && j < n; j++) {
            if (dp[j] !== Infinity) {
                dp[i] = Math.min(dp[i], 1 + dp[j]);
            }
        }
    }

    // If end cannot be reached.
    if (dp[0] === Infinity)
        return -1;

    return dp[0];
}

let arr = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9];
console.log(minJumps(arr));

Output
3

Related article:



Next Article

Similar Reads

three90RightbarBannerImg