How does recursive isPalindrome function work?

gryb picture gryb · Feb 2, 2012 · Viewed 13.4k times · Source

I'm working on some introductory recursion problems and I have a clarifying question I'd like to get answered. The most nagging question I have is how is this recursion operating in the solved problem below?

Despite having solved the problem, I'm just not understanding how the recursion call makes its way into the interior of the string. It would seem, from just looking at the code, that this method would only ever check the two characters on either end of the given string, without checking the rest. My textbook gives the deeply unsatisfying answer of, basically, don't worry about how recursion works as long as your return statement refines the problem. But I'm having difficulty knowing how to approach subsequent recursion problems without understanding how one can trace a recursive method in the same way one would trace a loop.

Any words of wisdom would be much appreciated.

Thanks!

public class isPalindrome {

public static boolean isPalindrome(String str)
{
    //test for end of recursion
    if(str.length() < 2) {return true;}

    //check first and last character for equality
    if(str.charAt(0) != str.charAt(str.length() - 1)){return false;}

    //recursion call 
    return isPalindrome(str.substring(1, str.length() - 1));
}
public static void main(String[] args)
{
    System.out.print(isPalindrome("deed"));
}
}

Answer

Nadir Muzaffar picture Nadir Muzaffar · Feb 2, 2012

The isPalindrome() function is recursively being called on str.substring(1, str.length() -1). So the callstack would look like this for the isPalindrome() calls:

1. isPalindrome("abcddcba"): 

   ("a" == "a") = true, so recurse

2. isPalindrome("bcddcb"):

   ("b" == "b") = true, so recurse

3. isPalindrome("cddc"):     

   ("c" == "c") = true, so recurse

4. isPalindrome("dd"): 

   ("d" == "d") = true, so recurse  

6. isPalindrome(""):           

   length < 2, so return true

The return value of the last call will propagate all the way to the top.

With recursion, pictures always help. Do your best to draw out the callstack as a diagram. It'll allow you to visualize, and therefore better understand, more complex recursions. This is a simple "linear" recursion but you'll eventually face "tree" like recursions.

Here's a picture that illustrates this exact problem for you to better visualize:

Palindrome recursion