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));
}
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).
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).
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).
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With