0

I have written a recursive function which computes Catalan Numbers. The recursion formula is enter image description here.

My code:

def catalan(n): # We call this function. To my opinion it is more elegant.
    d = dict()
    return catalan_rec(n,d)

def catalan_rec(n,d):
    if n == 0:
        result = 1
    elif n in d: return d[n]
    else:
        result = 0
        for i in range(n):
            result += catalan_rec(i,d)*catalan_rec(n-i-1,d)
        d[n] = result
    return result

Now, it is obvious that the recursion depth is O(n). I am not sure what is the time complexity of this algorithem. The recursion tree has O(n) nodes and in any node (except leaves) we make two calls. Any call is O(1) as we only check if we already have the result in the dictionary, hence the time complexity is O(n).

Is my reasoning correct?

And by the way, is there an option to write non recursive algorithm that runs in time complexity which is better than O(n^2)?

Thanks!

Guy Coder
  • 24,501
  • 8
  • 71
  • 136
Galc127
  • 175
  • 6
  • Python is probably not the best language for implementing recursive algorithms, as it does not have proper recursion support. I believe that, under ideal circumstances, your reasoning is correct, but your actual run-times may not reflect this if you are using Python. I would suggest that you look at Haskell or R. – Kwarrtz Aug 27 '15 at 05:35
  • Kwarrtz, I'm aware of python's disadvantages, but I'm taking a course in university and they decided to teach python. It was a test question I tried to solve. By the way, in runs preety quick, not far slower than Haskell. – Galc127 Aug 27 '15 at 05:38
  • @Galc127 not any call is `O(1)`. Notice, that you have `for i in range(n)` here. No way this would work in constant time :) – Konstantin Aug 27 '15 at 05:43
  • My suggestion was not out of consideration of performance (although I would have to see a benchmark to believe your claim), but rather for Python's fitness for running recursive algorithms. However, if the university course is in Python, you don't really have a choice. – Kwarrtz Aug 27 '15 at 05:44
  • @Galc127 The time _is_ `O(1)` if either of the first two branches are followed. – Kwarrtz Aug 27 '15 at 05:45
  • @Alik, so what is the time complexity? – Galc127 Aug 27 '15 at 05:45

1 Answers1

1

Not sure if this is what you want, but according to that page you could write the function to compute the catalan number in O(n) like this:

def catalan(n):
    num, div = 1, 1
    for x in range(n + 2, 2*n + 1):
        num *= x
    for x in range(2, n + 1):
        div *= x
    return num / div
Diego Basch
  • 12,764
  • 2
  • 29
  • 24