Counts Path in an Array - GeeksforGeeks

30 Apr, 2021
Given an array A consisting of positive integer, of size N. If the element in the array at index i is K then you can jump between index ranges (i + 1) to (i + K). The task is to find the number of possible ways to reach the end with module 109 + 7.The starting position is considered as index 0.Examples:  
Input: A = {5, 3, 1, 4, 3} Output: 6Input: A = {2, 3, 1, 1, 2} Output: 4  
 
Naive Approach: We can form a recursive structure to solve the problem.Let F[i] denotes the number of paths starting at index i, at every index i if the element A[i] is K then the total number of ways the jump can be performed is:  
F(i) = F(i+1) + F(i+2) +...+ F(i+k), where i + k <= n, 
where F(n) = 1
By using this recursive formula we can solve the problem: 
C++
Java
Python3
C#
Javascript
// C++ implementation of// the above approach#include <bits/stdc++.h>using namespace std; const int mod = 1e9 + 7; // Find the number of ways// to reach the endint ways(int i, int arr[], int n){    // Base case    if (i == n - 1)        return 1;     int sum = 0;     // Recursive structure    for (int j = 1;         j + i < n && j <= arr[i];         j++) {        sum += (ways(i + j,                     arr, n))               % mod;        sum %= mod;    }     return sum % mod;} // Driver codeint main(){    int arr[] = { 5, 3, 1, 4, 3 };     int n = sizeof(arr) / sizeof(arr[0]);     cout << ways(0, arr, n) << endl;     return 0;}
// Java implementation of// the above approachimport java.io.*; class GFG{static int mod = 1000000000; // Find the number of ways// to reach the endstatic int ways(int i,                int arr[], int n){    // Base case    if (i == n - 1)        return 1;     int sum = 0;     // Recursive structure    for (int j = 1; j + i < n &&                    j <= arr[i]; j++)    {        sum += (ways(i + j,                     arr, n)) % mod;        sum %= mod;    }    return sum % mod;} // Driver codepublic static void main (String[] args){    int arr[] = { 5, 3, 1, 4, 3 };         int n = arr.length;     System.out.println (ways(0, arr, n));}} // This code is contributed by ajit
# Python3 implementation of# the above approach mod = 1e9 + 7; # Find the number of ways# to reach the enddef ways(i, arr, n):         # Base case    if (i == n - 1):        return 1;     sum = 0;     # Recursive structure    for j in range(1, arr[i] + 1):        if(i + j < n):            sum += (ways(i + j, arr, n)) % mod;            sum %= mod;     return int(sum % mod); # Driver codeif __name__ == '__main__':    arr = [5, 3, 1, 4, 3];     n = len(arr);     print(ways(0, arr, n)); # This code is contributed by PrinciRaj1992
// C# implementation of// the above approachusing System;     class GFG{static int mod = 1000000000; // Find the number of ways// to reach the endstatic int ways(int i,                int []arr, int n){    // Base case    if (i == n - 1)        return 1;     int sum = 0;     // Recursive structure    for (int j = 1; j + i < n &&                    j <= arr[i]; j++)    {        sum += (ways(i + j,                     arr, n)) % mod;        sum %= mod;    }    return sum % mod;} // Driver codepublic static void Main (String[] args){    int []arr = { 5, 3, 1, 4, 3 };         int n = arr.Length;     Console.WriteLine(ways(0, arr, n));}} // This code is contributed by 29AjayKumar
<script>    // Javascript implementation of the above approach         let mod = 1000000000;       // Find the number of ways    // to reach the end    function ways(i, arr, n)    {        // Base case        if (i == n - 1)            return 1;         let sum = 0;         // Recursive structure        for (let j = 1; j + i < n && j <= arr[i]; j++)        {            sum += (ways(i + j, arr, n)) % mod;            sum %= mod;        }        return sum % mod;    }         let arr = [ 5, 3, 1, 4, 3 ];           let n = arr.length;       document.write(ways(0, arr, n));     </script>
6
 
Efficient Approach: In the previous approach, there are some calculations that are being done more than once. It will be better to store these values in a dp array and dp[i] will store the number of paths starting at index i and ending at the end of the array.Hence dp[0] will be the solution to the problem.Below is the implementation of the approach: 
C++
Java
Python3
C#
Javascript
// C++ implementation#include <bits/stdc++.h>using namespace std; const int mod = 1e9 + 7; // find the number of ways to reach the endint ways(int arr[], int n){    // dp to store value    int dp[n + 1];     // base case    dp[n - 1] = 1;     // Bottom up dp structure    for (int i = n - 2; i >= 0; i--) {        dp[i] = 0;         // F[i] is dependent of        // F[i+1] to F[i+k]        for (int j = 1; ((j + i) < n                         && j <= arr[i]);             j++) {            dp[i] += dp[i + j];            dp[i] %= mod;        }    }     // Return value of dp[0]    return dp[0] % mod;} // Driver codeint main(){    int arr[] = { 5, 3, 1, 4, 3 };     int n = sizeof(arr) / sizeof(arr[0]);     cout << ways(arr, n) % mod << endl;    return 0;}
// Java implementation of above approachclass GFG{    static final int mod = (int)(1e9 + 7);         // find the number of ways to reach the end    static int ways(int arr[], int n)    {        // dp to store value        int dp[] = new int[n + 1];             // base case        dp[n - 1] = 1;             // Bottom up dp structure        for (int i = n - 2; i >= 0; i--)        {            dp[i] = 0;                 // F[i] is dependent of            // F[i+1] to F[i+k]            for (int j = 1; ((j + i) < n &&                              j <= arr[i]); j++)            {                dp[i] += dp[i + j];                dp[i] %= mod;            }        }             // Return value of dp[0]        return dp[0] % mod;    }         // Driver code    public static void main (String[] args)    {        int arr[] = { 5, 3, 1, 4, 3 };             int n = arr.length;             System.out.println(ways(arr, n) % mod);    }} // This code is contributed by AnkitRai01
# Python3 implementation of above approachmod = 10**9 + 7 # find the number of ways to reach the enddef ways(arr, n):         # dp to store value    dp = [0] * (n + 1)         # base case    dp[n - 1] = 1         # Bottom up dp structure    for i in range(n - 2, -1, -1):        dp[i] = 0                 # F[i] is dependent of        # F[i + 1] to F[i + k]        j = 1        while((j + i) < n and j <= arr[i]):            dp[i] += dp[i + j]            dp[i] %= mod            j += 1         # Return value of dp[0]    return dp[0] % mod # Driver codearr = [5, 3, 1, 4, 3 ]n = len(arr)print(ways(arr, n) % mod) # This code is contributed by SHUBHAMSINGH10
// C# implementation of above approachusing System;     class GFG{    static readonly int mod = (int)(1e9 + 7);         // find the number of ways to reach the end    static int ways(int []arr, int n)    {        // dp to store value        int []dp = new int[n + 1];             // base case        dp[n - 1] = 1;             // Bottom up dp structure        for (int i = n - 2; i >= 0; i--)        {            dp[i] = 0;                 // F[i] is dependent of            // F[i+1] to F[i+k]            for (int j = 1; ((j + i) < n &&                              j <= arr[i]); j++)            {                dp[i] += dp[i + j];                dp[i] %= mod;            }        }             // Return value of dp[0]        return dp[0] % mod;    }         // Driver code    public static void Main (String[] args)    {        int []arr = { 5, 3, 1, 4, 3 };             int n = arr.Length;             Console.WriteLine(ways(arr, n) % mod);    }} // This code is contributed by Rajput-Ji
<script>     // Javascript implementation    // of above approach         let mod = (1e9 + 7);           // find the number of ways    // to reach the end    function ways(arr, n)    {        // dp to store value        let dp = new Array(n + 1);        dp.fill(0);               // base case        dp[n - 1] = 1;               // Bottom up dp structure        for (let i = n - 2; i >= 0; i--)        {            dp[i] = 0;                   // F[i] is dependent of            // F[i+1] to F[i+k]            for (let j = 1; ((j + i)            < n && j <= arr[i]); j++)            {                dp[i] += dp[i + j];                dp[i] %= mod;            }        }               // Return value of dp[0]        return dp[0] % mod;    }         let arr = [ 5, 3, 1, 4, 3 ];           let n = arr.length;     document.write(ways(arr, n) % mod);     </script>
6
 
Time Complexity: O(K) 
jit_t
29AjayKumar
ankthon
Rajput-Ji
princiraj1992
SHUBHAMSINGH10
rameshtravel07
divyesh072019
tail-recursion
Arrays
Dynamic Programming
Arrays
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16