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 a given string using a stack data structure. As the stack is involved, we can easily convert the code to use the call stack.

The implementation can be seen below in C and C++:

C


Download  Run Code

C++


Download  Run Code

Approach 2

The 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 approach #3 discussed here.

Following is the implementation in C, C++, and Java based on the above idea:

C


Download  Run Code

C++


Download  Run Code

Java


Download  Run Code

The time complexity of both above-discussed methods is O(n) and requires O(n) implicit space for the call stack, where n is the length of the input string.