5

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));
}
Misha Moroshko
  • 148,413
  • 200
  • 467
  • 700

1 Answers1

4

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).

gurvinder372
  • 61,170
  • 7
  • 61
  • 75
  • @Thilo Please check now – gurvinder372 May 27 '16 at 09:40
  • 1
    Definitely. More precisely the complexity consists in a Fibonacci series. – dgiugg May 27 '16 at 11:09
  • @dgiugg yes, it looks quite close doesn't it? http://stackoverflow.com/questions/360748/computational-complexity-of-fibonacci-sequence – gurvinder372 May 27 '16 at 11:10
  • 1
    Yes, the worst case is exactly a Fibonacci suite. The mean case is the same with different coefficients : Fn+2 = Fn+1 + 3/4Fn. The 3/4 is for 26/100 cases with the comparison to 26. – dgiugg May 27 '16 at 11:14