the blog for developers

String reversing Part II: Tail Recursion

As several people pointed out in my last post that my version of reversing a string with recursion wasn’t tail recursive despite the fact that I wrongly thought it was. Not that it’s important in the context of a job interview for Java developers, whether one uses tail recursion or not. But I thought nevertheless about a Java tail recursive solution. Reading more about tail recursion in several articles and the comments of the last post, I wrote a new version of the String reversal solution. This time with tail recursion. So as a service to the interested reader:

      public String reverse(String str) {
          if ((null == str) || (str.length()  <= 1)) {
              return str;
          }
          return reverse(str, "");
      }

      private String reverse(String str, String acc) {
        if (str.length() == 0) {
          return acc;
        } else {
          return reverse(str.substring(1), str.charAt(0) + acc);
        }
      }

Tail recursion means, the last call in the recursive function is a call to the function and there is nothing left to do when the recursive call returns. Why tail recursion? With tail recursion it's easy for the compiler to remove the recursion and drop the growing stack. So with an optimized tail recursive function you will not run out of stack space what you otherwise would quite easily.

Update: For comparison the non-tail recursive solution.

        public String reverse(String str) {
            if ((null == str) || (str.length()  <= 1)) {
                return str;
            }
            return reverse(str.substring(1)) + str.charAt(0);
        }

Update 2: The call stack for the recursive solution for "ABC" would be:

-> reverse("ABC")
-> reverse("BC") + 'A'
-> (reverse("C") + 'B') + 'A'
-> ("C" + 'B') + 'A'
-> "CB" + 'A'
-> "CBA"

and for the tail recursive version:
-> reverse("ABC", "")
-> reverse("BC", "A")
-> reverse("C", "BA")
-> reverse("", "CBA")
-> "CBA"

Comparing those two the first one increases the stack to a point until it starts to pop the stack. The tail recursive version does not use the stack to keep a "memory" what it has still to do, but calculates the result imediatly. Comparing the source though, in my view the tail recursive version takes all beauty out of the recursive implementation. It nearly looks iterative.

You can leave a Reply here. Of course, you should follow me on twitter here.

You can share this post!
Do you want to tell others about this article? Use the social bookmark icons to submit this artice to the service of your choice. Thanks.

About the author: Stephan Schmidt has more than 15 years of internet technology experience and 10 years experience in agile. He was head of development, consultant and CTO and is a speaker, author and blog writer. He specializes in organizing and optimizing software development helping companies by increasing productivity with lean software development and agile methodologies. Want to know more? All views are only his own.
Leave a reply.

Comments

mccoyn

I agree, tail recursion optimizations take the beauty out of recursion. Some things can be solved very beautifully with recursion until you realize the stack frame or speed implications make it an unscaleable solution.

I know a lot of interpreted languages represent the stack as a linked list, or even a linked tree. This gets around the limits on stack space, but makes function calls a little slower.

I haven’t seen any compliers that attempt to make recursion faster other than with the tail-recursion optimization.

stephan

Reading through lambda the ultimate some compilers seem to automatically change recursion to tail recursion, so the beauty in the source is preserved. But I’m no specialist in functional programming.

Hi Stephan,

Kudo’s for following up with the tail recursion example. Personally, unless your a LISPer, I find that tail recursive solutions are better expressed iteratively.

But thats just my opinion, and its been considered faulty before :)

stephan

;-)

[...] A Recursive version from here [...]

Javier Mena

I was intensive tail recursion use in java, but I “discovered” that sun jvm (at least for java 1.5) doesn’t optimizes for tail recursion.

Try to implement a recursive fact with a large number, and it will raise a stack overflow exception.

There are many developers that don’t understand tail recursion. :(

Leave a Reply

What people wrote somewhere else:

Additional comments powered by BackType

Guide to CodeMonkeyism

Over the last 4 years I wrote many articles on this blog. To make it easier for you to find the relevant ones, I've organized them into topics.

Top 10

6 reasons why my VC funded startup did fail

Go Ahead: Next Generation Java Programming Style

Java Interview questions: Write a String Reverser

The dark side of NoSQL

7 Bad Signs not to Work for a Software Company or Startup

Is Java dead?

Scala vs. Clojure

Never, never, never use String in Java

No future for functional programming in 2008 – Scala, F# and Nu

Clojure vs Scala, Part 2

Java Developer

Is Java Dead?

Go Ahead: Next Generation Java Programming Style

Be careful with magical code

All variables in Java must be final

Never, never, never use String in Java

Bending Java: More readable code with methods that do nothing?

NoSQL Guy

NoSQL: The Dawn of Polyglot Persistence

The dark side of NoSQL

Essential storage tradeoff: Simple Reads vs. Simple Writes

Sharding destroys the goals of your relational database

The unholy legacy of databases

Startup/CTO

Development Dream Teams

6 reasons why my VC funded startup did fail

American vs. European style of Software Development

12 Things to Reduce Your Lead Time and Time to Market

The high cost of overhead when working in parallel

Essential storage tradeoff: Simple Reads vs. Simple Writes

Job Seeker

Another Good (Java) Interview Question

7 Bad Signs not to Work for a Software Company or Startup

Java Interview questions: Write a String Reverser (and use Recursion!)

Java Interview questions: Multiple Inheritance

As a Manager: What I value in developers

Top 10 Tips (+1) to Get a Pay Raise

Agilist

What Developers Need to Know About Agile

5 Practices Better to Change in Your Scrum Implementation

Scrum is not about engineering practices

ScrumMaster and ZenMaster: The joke of certification

What is Trans-Scrum?