Open In App

Print reverse of a string using recursion

Last Updated : 06 Mar, 2025
Comments
Improve
Suggest changes
58 Likes
Like
Report

Given a string, the task is to print the given string in reverse order using recursion.

Examples:

Input: s = “Geeks for Geeks”
Output: “skeeG rof skeeG
Explanation: After reversing the input string we get skeeG rof skeeG“.

Input: s = “Reverse a string Using Recursion”
Output: “noisruceR gnisU gnirts a esreveR
Explanation: After reversing the input string we get noisruceR gnisU gnirts a esreveR.

[Approach – 1] – Make a Recursive Call and Then Process the First Char

The idea for this approach is to make a recursive call for the substring starting from the second character and then print the first character.

C++
#include <bits/stdc++.h>
using namespace std;

string reverse(string str) 
{ 
    if(str.size() == 0)
        return str;
    return reverse(str.substr(1)) + str[0];
}

int main() 
{ 
    string str = "Geeks for Geeks"; 
    cout << reverse(str); 
    return 0; 
} 
C Java Python C# JavaScript

Output
skeeG rof skeeG

Time Complexity: O(n)
Auxiliary Space: O(n)

[Approach – 2] – Process the Last Char and Then Make Recursive Call

This idea is to break the problem in terms of smaller instance of same subproblem.
str= “Geeks for geeks”
reverse string of str = last character of str + reverse string of remaining str = “s” + reverse string of “Geeks for geek” = “skeeg rof skeeG”

C++
#include <bits/stdc++.h>
using namespace std;

string reverse(string str, int len)
{
    if (len < 1)
    {
        return "";
    }
    // Base case
    if (len == 1)
    {
        return string(1, str[0]);
    }
    return str[len - 1] + reverse(str, len - 1);
}

int main()
{
    string str = "Geeks for geeks";
    cout << reverse(str, str.length()) << endl;
    return 0;
}
Java Python C# JavaScript

Output
skeeg rof skeeG

Time Complexity: O(n)
Auxiliary Space: O(n)

[Approach – 3] – Optimized- Process from Both Ends

The idea is to begin with both corners, swap the corner characters and then make recursive call for the remaining string.

C++
#include <bits/stdc++.h>
using namespace std;

void reverse(string &str, int start, int end) 
{
    if (start >= end) 
        return;
    swap(str[start], str[end]);
    reverse(str, start + 1, end - 1);
}

int main() 
{ 
    string str = "Geeks for Geeks"; 
    reverse(str, 0, str.size() - 1);
    cout << str;  
    return 0; 
}
Java Python JavaScript

Time Complexity: O(n)
Auxiliary Space: O(n)




Next Article
Article Tags :
Practice Tags :

Similar Reads