HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Reversing strings using recursion

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
stringsreversingusingrecursion

Problem

I'm trying to solve exercises where I am required to use recursion. I wrote this:

static String reverse(String word){
    if(word.length()<2){
        return word;
    }
    else{
        int index = word.length() - 1;
        return word.charAt(index) + reverse(word.substring(0, index));
    }
}


But the answer for that question was the following code:

static String reverseRecursively(String str) {
    //base case to handle one char string and empty string
    if (str.length() < 2) {
        return str;
    }

    return reverseRecursively(str.substring(1)) + str.charAt(0);

}


And now let's suppose that you are a recruiter and got the first solution. Do you accept it? If not, why? What should I do better?

Solution

In production Java code, you would never reverse a string using recursion, primarily due to efficiency concerns, and also because new StringBuilder(str).reverse().toString() is better. Therefore, this question should be treated as an academic exercise — a quick test to weed out candidates who don't understand recursion at all. I don't think that an optimal solution is required.

Basically, your solution is good enough. That said…

  • I prefer your reverse() to reverseRecursively(), since I consider the recursion to be an implementation detail that doesn't need to be reflected in the name.



  • str is a more appropriate parameter name, since the function doesn't care whether the string is a word or not.



  • The way you sliced the string is less elegant than in the second solution.



  • I find your brace style slightly irksome. (Normally I wouldn't say anything about it, but given how little code I have been given to evaluate, I'm judging you on that.) Try to stick to the obsolete official Java style guide or Google's Java style guide, which is a close derivative of it.

Context

StackExchange Code Review Q#92388, answer score: 5

Revisions (0)

No revisions yet.