Answers ( 3 )

  1. 2016-12-31 22:12

    Space complexity is O(n) because one side of recursion, reaches the leaves, and returns up, until the root, similar happens for the other side of recursion and in every middle step, the space used in the recursion cannot be bigger than O of depth of recursion tree.

  2. 2016-12-31 22:12

    Because the second f(n-1) can't run until the first one completes (or vice versa -- it's the same either way). The first call will recurse n times, then all those will return, so that will push a total of n stack frames. Then the second call will do the same thing.

    So it never gets more than n levels deep in the recursion, and that's the only contributor to space complexity.

  3. 2016-12-31 22:12

    Draw the exponential time complexity tree and the length of path of any leaf from the root of the tree will be linear. This linear path is the space complexity of the algorithm. The algorithm will traverse each of those paths to solve the problem but at any point the maximum number of recursive calls stored in the stack will be linear. Ex: for f(3)

             3 
           /   \ 
         2      2 
        / \    / \ 
       1   1  1   1
    

    The maximum length from root to leaf is O(n). Thus, the space complexity is also O(n).

◀ Go back