Recursion with 2 arguments inside a loop Time Complexity

EranMa 21 Reputation points
2021-07-15T10:12:25.303+00:00

I try to find the time complexity of this recursive function, how can I solve this?

lets assume the inputs are positive numbers, and valid steps is a unique list

ex:

validsteps = [1,2] distance = 3

validsteps = [1,2,3] distance = 4

'''C#

int countpaths(int[] validsteps, int distance)
    {
        if (distance == 0)
        {
            return 1;
        }

        int paths = 0; 

        foreach (int step in validsteps)
        {
            if (distance >= step)
            {
                paths += countpaths(validsteps, distance - step);
            }

        }

        return paths;
    }
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,131 questions
0 comments No comments
{count} votes

Accepted answer
  1. Xingyu Zhao-MSFT 5,356 Reputation points
    2021-07-16T06:12:09.82+00:00

    Hi @EranMa ,
    This method has no fixed time complexity.
    Suppose the length of 'validsteps' is N, the value of 'distance' is k.
    In the best case, the time complexity is O(1):

    K <= Min(validsteps)  
    

    For example:

    validsteps = [2,3,4] distance = 1  
    

    In the worst case,the time complexity is O( K power of 2) : O(2 k )

    K = Max(validsteps) validsteps = [1,2,3,...,N]  
    

    For example:

    validsteps = [1,2,3,4] distance = 4  
    

    Generally, the range of time complexity is between O(1) and O(K power of 2).
    Hope it could be helpful.

    Best Regards,
    Xingyu Zhao
    *
    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful