Print reverse of a string using recursion
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.
#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;
}
#include <stdio.h>
void reverse(const char *str)
{
if (*str == '\0')
return;
reverse(str + 1);
putchar(*str);
}
int main()
{
char str[] = "Geeks for Geeks";
reverse(str);
return 0;
}
public class Main {
public static String reverse(String str) {
if (str.isEmpty())
return str;
return reverse(str.substring(1)) + str.charAt(0);
}
public static void main(String[] args) {
String str = "Geeks for Geeks";
System.out.println(reverse(str));
}
}
# Function to reverse a string
def reverse(str):
if len(str) == 0:
return str
return reverse(str[1:]) + str[0]
# Main function
if __name__ == '__main__':
str = 'Geeks for Geeks'
print(reverse(str))
using System;
class Program {
static string Reverse(string str) {
if (str.Length == 0)
return str;
return Reverse(str.Substring(1)) + str[0];
}
static void Main() {
string str = "Geeks for Geeks";
Console.WriteLine(Reverse(str));
}
}
// Function to reverse a string
function reverse(str) {
if (str.length === 0)
return str;
return reverse(str.substring(1)) + str[0];
}
// Main function
const str = 'Geeks for Geeks';
console.log(reverse(str));
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”
#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;
}
import java.util.*;
public class GfG {
// Function to reverse a string using recursion
public static String reverse(String str, int len)
{
if (len < 1) {
return "";
}
// Base case
if (len == 1) {
return String.valueOf(str.charAt(0));
}
return str.charAt(len - 1) + reverse(str, len - 1);
}
public static void main(String[] args)
{
String str = "Geeks for geeks";
System.out.println(reverse(str, str.length()));
}
}
def reverse(string, length):
if length < 1:
return ""
# Base case
if length == 1:
return string[0]
return string[length - 1] + reverse(string, length - 1)
if __name__ == "__main__":
str = "Geeks for geeks"
print(reverse(str, len(str)))
using System;
class GfG {
static string Reverse(string str, int len)
{
// Base case: If the string length is less than 1,
// return an empty string
if (len < 1) {
return "";
}
// Base case: If the string has only one character,
// return that character as a string
if (len == 1) {
return str[0].ToString();
}
// Recursive case: Concatenate the last character of
// the string with the reversed substring
return str[len - 1] + Reverse(str, len - 1);
}
static void Main()
{
string str = "Geeks for geeks";
// Call the Reverse function and print the reversed
// string
Console.WriteLine(Reverse(str, str.Length));
}
}
function reverse(str, len)
{
if (len < 1) {
return
}
// base case
if (len === 1) {
return str[0]
}
return str[len - 1] + reverse(str, len - 1)
}
// Driver code
let str = "Geeks for geeks"
console.log(reverse(str, str.length))
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.
#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 program to reverse a string
class ReverseString {
static void reverse(StringBuilder str, int start, int end) {
if (start >= end)
return;
char temp = str.charAt(start);
str.setCharAt(start, str.charAt(end));
str.setCharAt(end, temp);
reverse(str, start + 1, end - 1);
}
public static void main(String[] args) {
StringBuilder str = new StringBuilder("Geeks for Geeks");
reverse(str, 0, str.length() - 1);
System.out.println(str);
}
}
# Python program to reverse a string
def reverse(str, start, end):
if start >= end:
return
str[start], str[end] = str[end], str[start] # Swap characters
reverse(str, start + 1, end - 1)
if __name__ == '__main__':
str = list("Geeks for Geeks")
reverse(str, 0, len(str) - 1)
print(''.join(str))
// JavaScript implementation
function reverse(str, start, end) {
if (start >= end)
return;
str = str.split('');
[str[start], str[end]] = [str[end], str[start]];
str = str.join('');
reverse(str, start + 1, end - 1);
return str;
}
let str = "Geeks for Geeks";
str = reverse(str, 0, str.length - 1);
console.log(str);
Time Complexity: O(n)
Auxiliary Space: O(n)