Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Space complexity of recursive algorithm

I was asked at an interview, the efficient way to solve a problem checking for pallindrome.

Now i can do two things:

  1. starting from i = 0 to i = n/2 and comparing ith and n-ith character to be equal.
  2. I can use recursion to check if first and last are same and the rest of the string is a pallindrome.

The second is recursive. My question is what is the difference in the space complexity of an algorithm's recursive and non-recursive versions?

like image 306
dharam Avatar asked May 30 '12 17:05

dharam


People also ask

What is space and time complexity of recursive factorial algorithm?

Therefore, The time complexity of recursive factorial is O(n). As there is no extra space taken during the recursive calls,the space complexity is O(N).

Is recursive stack counted in space complexity?

Stack space in recursive calls counts too as extra space required by a program.

What is the space complexity of DFS?

The space complexity for DFS is O(h) where h is the maximum height of the tree.

How do you calculate space complexity of an algorithm?

So, the space occupied by the array is 4 * n. Also we have integer variables such as n, i and sum. Assuming 4 bytes for each variable, the total space occupied by the program is 4n + 12 bytes. Since the highest order of n in the equation 4n + 12 is n, so the space complexity is O(n) or linear.


2 Answers

Have a read at

  1. http://www.codeproject.com/Articles/21194/Iterative-vs-Recursive-Approaches
  2. Recursion or Iteration?

Basically, a recursive algorithm will add overhead since you store recursive calls in the execution stack.

But if the recursive function is the last line of the call (tail recursion) then there is no additional penalty.

That is of course both algorithms are the same.

like image 73
Yannis Avatar answered Sep 24 '22 13:09

Yannis


In theory they have the same space complexity; it largely depends on whether tail recursion can be optimized.

If so, the stack gets replaced at every recursion so it doesn't incur a penalty.

like image 22
Ja͢ck Avatar answered Sep 20 '22 13:09

Ja͢ck