Given a string, print it backwards using recursion.

For example, consider the input string “Techie Delight”. The output should be “thgileD eihceT”.

 
As seen in the previous post, we can easily reverse a string using the stack data structure. Since the stack is involved, we can easily modify the code to use the call stack. As recursion finishes, print the characters stored in the call stack one by one.

Following is the C, C++, Java, and Python program that demonstrates it:

C


Download  Run Code

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

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