10

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?

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
dharam
  • 7,882
  • 15
  • 65
  • 93

2 Answers2

10

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.

Community
  • 1
  • 1
Yannis
  • 6,047
  • 5
  • 43
  • 62
1

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.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • For large data sets , even with tail recursion , will lead to StackOverflow error . No? – Sudhakar Jul 02 '13 at 14:25
  • @Sudhakar That's exactly what tail recursion optimisation prevents :) – Ja͢ck Jul 02 '13 at 22:47
  • Is this program a valid example of Tail Recursion. This produces stackoverflow . Pls correct me if iam wrong.
    public class TailTest {
    
     public static void main(String[] args) {
      System.out.println(TailTest.iterate(100000));
     }
     
     public static long iterate(int n){
      if(n==1) return 1;  
      return iterate(n-1);
     }
    }
    
    – Sudhakar Jul 03 '13 at 14:23
  • @Sudhakar In that case, there's no tail recursion *optimisation* being done. – Ja͢ck Jul 03 '13 at 15:20