String Reversal in JAVA with O(n * log(n))

A normal String Reversal program may take a brute force method with O(n). But with the help of recursion we can reduce the complexity, making it as O(n* log(n)).

Input: mahabaleshwar

Output: rawhselabaham

public class StringUtility{

     public static String getReverse(String in){
           int length = s.length();
           
           if(length <= 1)
              return in;
    
           String leftSubStr = in.substring(0, length / 2);
           String rightSubStr = in.substring(length / 2, length );

           return getReverse(rightSubStr) + getReverse(leftSubStr);
     }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s