Search code examples
pythonrecursiontime-complexitybig-ospace-complexity

Determining time and space complexity of a recursive function


def foo(n):
    def bar(n):
        if n == 0: 
            return 0
        else:
            return 1 + bar (n - 1)
    return n * bar(n)

How can I calculate what is the time complexity for the running time of foo in terms of its input n? What about space complexity?


Solution

  • Let's break it down:

     return n * bar(n)
          → n * (1 + bar(n - 1))
          → n * (1 + 1 + bar(n - 2))
          → n * (1 + 1 + 1 + bar(n - 3))
          → n * (1 + 1 + 1 + .... <n times> + bar(0))
          → n * n
    

    This appears linear in time and memory - O(n).