Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the complexity of a recursive function?

Tags:

What's the most intuitive way to calculate the time and space complexity (Big O notation) of the following recursive function?

function count(str) {
  if (str.length <= 1) {
    return 1;
  }

  var firstTwoDigits = parseInt(str.slice(0, 2), 10);

  if (firstTwoDigits <= 26) {
    return count(str.slice(1)) +
           count(str.slice(2));
  }

  return count(str.slice(1));
}
like image 420
Misha Moroshko Avatar asked May 27 '16 09:05

Misha Moroshko


People also ask

What is the time complexity for recursion?

Since Sum(1) is computed using a fixed number of operations k1, T(1) = k1. If n > 1 the function will perform a fixed number of operations k2, and in addition, it will make a recursive call to Sum(n-1) . This recursive call will perform T(n-1) operations. In total, we get T(n) = k2 + T(n-1).

What is the big O of a recursive function?

The big-O runtime for a recursive function is equivalent to the number of recursive function calls. This value varies depending on the complexity of the algorithm of the recursive function. For example, a recursive function of input N that is called N times will have a runtime of O(N).

Is recursion O 1 space complexity?

Recursive Solution Each call maintains a record on the activation stack. The stack holds a copy of the variables n and result . Hence, the space complexity of the recursive version of factorial is O(n).

How do you find the time complexity of a recursive function in Java?

Draw a recursive tree for given recurrence relation. Calculate the cost at each level and count the total no of levels in the recursion tree. Count the total number of nodes in the last level and calculate the cost of the last level. Sum up the cost of all the levels in the recursive tree.


1 Answers

Apologies for my prev answer, Complexity of your code seems to be

O(2^N) or O(2^N-1) to be precise in worst case scenario.

So, If

N = str.length ;//number of iteration

In the worst case scenario, your str consists of all N digits of either 1 or 2.

Then, If N is 20 to begin with, then it will spawn two more recursive calls of N= 18 and N = 19,

Then, N = 19 will spawn two more calls (and so one till value of N is 0 )

So, the number of calls will increase exponentially with each iteration), hence coming to the value (2^N - 1).

like image 104
gurvinder372 Avatar answered Sep 28 '22 03:09

gurvinder372