Reverse a given string using Recursion in C, C++, and Java

Write a recursive program to efficiently reverse a given string in C, C++ and Java.

 

For example,


Input: Techie Delight

Output: thgileD eihceT

 

 

Approach 1:

As seen in the previous post, we can easily reverse given string using stack data structure. As stack is involved, we can easily convert the code to use function call stack.

C

Download   Run Code

C++

Download   Run Code

 

Approach 2:

Above solution uses a static variable which is not recommended. We can easily solve this problem without using any static variable. This approach is almost similar to the Approach #3 discussed here.

C

Download   Run Code

C++

Download   Run Code

Java

Download   Run Code

 
The time complexity of both solutions is O(n) and total space used is O(n) for function call stack.

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Get great deals at Amazon




Leave a Reply

avatar
  Subscribe  
Notify of