The Wayback Machine - https://web.archive.org/web/20241001215649/https://www.geeksforgeeks.org/reverse-a-string-using-recursion/
Open In App

Print reverse of a string using recursion

Last Updated : 16 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Write a recursive function to print the reverse of a given string. 
Code: 

C++




// C++ program to reverse a string using recursion
#include <bits/stdc++.h>
using namespace std;
 
/* Function to print reverse of the passed string */
void reverse(string str)
{
    if(str.size() == 0)
    {
        return;
    }
    reverse(str.substr(1));
    cout << str[0];
}
 
/* Driver program to test above function */
int main()
{
    string a = "Geeks for Geeks";
    reverse(a);
    return 0;
}
 
// This is code is contributed by rathbhupendra


C




// C program to reverse a string using recursion
# include <stdio.h>
 
/* Function to print reverse of the passed string */
void reverse(char *str)
{
   if (*str)
   {
       reverse(str+1);
       printf("%c", *str);
   }
}
 
/* Driver program to test above function */
int main()
{
   char a[] = "Geeks for Geeks";
   reverse(a);
   return 0;
}


Java




// Java program to reverse a string using recursion
 
class StringReverse
{
    /* Function to print reverse of the passed string */
    void reverse(String str)
    {
        if ((str==null)||(str.length() <= 1))
           System.out.println(str);
        else
        {
            System.out.print(str.charAt(str.length()-1));
            reverse(str.substring(0,str.length()-1));
        }
    }
     
    /* Driver program to test above function */
    public static void main(String[] args)
    {
        String str = "Geeks for Geeks";
        StringReverse obj = new StringReverse();
        obj.reverse(str);
    }   
}


Python




# Python program to reverse a string using recursion
 
# Function to print reverse of the passed string
def reverse(string):
    if len(string) == 0:
        return
     
    temp = string[0]
    reverse(string[1:])
    print(temp, end='')
 
# Driver program to test above function
string = "Geeks for Geeks"
reverse(string)
 
# A single line statement to reverse string in python
# string[::-1]
 
# This code is contributed by Bhavya Jain


C#




// C# program to reverse
// a string using recursion
using System;
 
class GFG
{
    // Function to print reverse
    // of the passed string
    static void reverse(String str)
    {
        if ((str == null) || (str.Length <= 1))
        Console.Write(str);
     
        else
        {
            Console.Write(str[str.Length-1]);
            reverse(str.Substring(0,(str.Length-1)));
        }
    }
     
    // Driver Code
    public static void Main()
    {
        String str = "Geeks for Geeks";
        reverse(str);
    }
}
 
// This code is contributed by Sam007


Javascript




<script>
        // JavaScript Program for the above approach
 
 
        /* Function to print reverse of the passed string */
        function reverse(str, len) {
            if (len == str.length) {
                return;
            }
            reverse(str, len + 1);
 
            document.write(str[len]);
 
        }
 
        /* Driver program to test above function */
 
        let a = "Geeks for Geeks";
 
        reverse(a, 0);
 
    // This code is contributed by Potta Lokesh
    </script>


PHP




<?php
// PHP program to reverse
// a string using recursion
 
// Function to print reverse
// of the passed string
function reverse($str)
{
    if (($str == null) ||
        (strlen($str) <= 1))
    echo ($str);
 
    else
    {
        echo ($str[strlen($str) - 1]);
        reverse(substr($str, 0,
               (strlen($str) - 1)));
    }
}
 
// Driver Code
$str = "Geeks for Geeks";
reverse($str);
 
// This code is contributed by
// Manish Shaw(manishshaw1)
?>


Output: 
 

skeeG rof skeeG

Explanation: Recursive function (reverse) takes string pointer (str) as input and calls itself with next location to passed pointer (str+1). Recursion continues this way when the pointer reaches ‘\0’, all functions accumulated in stack print char at passed location (str) and return one by one.

Time Complexity: O(n) where n is the length of string
See Reverse a string for other methods to reverse string.
Auxiliary Space: O(n)

Efficient Approach: 

We can store each character in recursive stack and then can print while coming back as shown in the below code: 

C++




// C++ program to reverse a string using recursion
#include <bits/stdc++.h>
using namespace std;
 
/* Function to print reverse of the passed string */
void reverse(char *str, int index, int n)
{
    if(index == n)      // return if we reached at last index or at the end of the string
    {
        return;
    }
    char temp = str[index];    // storing each character starting from index 0 in function call stack;
    reverse(str, index+1, n);  // calling recursive function by increasing index everytime
    cout << temp;              // printing each stored character while recurring back
}
 
/* Driver program to test above function */
int main()
{
    char a[] = "Geeks for Geeks";
    int n = sizeof(a) / sizeof(a[0]);
    reverse(a, 0, n);
    return 0;
}
 
// This is code is contributed by anuragayu


C




// C program to reverse a string using recursion
 
#include <stdio.h>
 
/* Function to print reverse of the passed string */
void reverse(char *str, int index, int n)
{
    if(index == n)      // return if we reached at last index or at the end of the string
    {
        return;
    }
    char temp = str[index];    // storing each character starting from index 0 in function call stack;
    reverse(str, index+1, n);  // calling recursive function by increasing index everytime
    printf("%c", temp);              // printing each stored character while recurring back
}
 
/* Driver program to test above function */
 
int main() {
   
    char a[] = "Geeks for Geeks";
    int n = sizeof(a) / sizeof(a[0]);
    reverse(a, 0, n);
    return 0;
}
 
// This is code is contributed by anuragayu


Java




/*package whatever //do not write package name here */
import java.io.*;
 
class GFG {
 
  /* Function to print reverse of the passed string */
  static void reverse(char[] str, int index, int n)
  {
    if (index == n) // return if we reached at last index or at the end of the string
    {
      return;
    }
    char temp = str[index]; // storing each character starting from index 0 in function call stack;
    reverse(str, index + 1, n); // calling recursive function by increasing index everytime
    System.out.print(temp); // printing each stored character while recurring back
  }
 
  public static void main(String[] args)
  {
    char a[] = "Geeks for Geeks".toCharArray();
    int n = a.length;
    reverse(a, 0, n);
  }
}
 
// This code is contributed by aadityaburujwale.


Python3




# Python3 program to reverse a string using recursion
def reverse(string, index, n):
    if index == n:   # return if we reached at last index or at the end of the string
        return
    temp = string[index]   # storing each character starting from index 0 in function call stack;
    reverse(string, index+1, n)  # calling recursive function by increasing index everytime
    print(temp, end="")   # printing each stored character while recurring back
 
# Driver code
string = "Geeks for Geeks"
n = len(string)
reverse(string, 0, n)
 
# This code is contributed by Potta Lokesh


C#




// Include namespace system
using System;
 
public class GFG
{
  // Function to print reverse of the passed string
  public static void reverse(char[] str, int index, int n)
  {
    if (index == n)
    {
      // return if we reached at last index or at the end of the string
      return;
    }
    var temp = str[index];
 
    // storing each character starting from index 0 in function call stack;
    GFG.reverse(str, index + 1, n);
 
    // calling recursive function by increasing index everytime
    Console.Write(temp);
  }
  public static void Main(String[] args)
  {
    char[] a = "Geeks for Geeks".ToCharArray();
    var n = a.Length;
    GFG.reverse(a, 0, n);
  }
}
 
// This code is contributed by aadityaburujwale.


Javascript




// JavaScript program to reverse a string using recursion
 
function reverse(string, index, n) {
if (index === n) { // return if we reached at last index or at the end of the string
return;
}
var temp = string[index]; // storing each character starting from index 0 in function call stack;
reverse(string, index+1, n); // calling recursive function by increasing index everytime
console.log(temp); // printing each stored character while recurring back
}
 
// Driver code
var string = "Geeks for Geeks";
var n = string.length;
reverse(string, 0, n);
 
// This code is contributed by pradeepkumarppk2003


Output:

skeeG rof skeeG

Time Complexity: O(n) where n is size of the string

Auxiliary Space: O(n) where n is the size of string, which will be used in the form of function call stack of recursion.

C++




#include <iostream>
using namespace std;
 
// Function to reverse a string using recursion
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;
}
 
// This code is contributed by akshitaguprzj3


Java




import java.util.*;
 
public class Main {
    // 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()));
    }
}


Python3




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__":
    input_str = "Geeks for geeks"
    print(reverse(input_str, len(input_str)))


C#




using System;
 
class Program
{
    // Function to reverse a string using recursion
    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));
    }
}


Javascript




// Javascript program to reverse string using recursion
 
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))
  
 // This code is contributed by rithikpathak123


Output

skeeg rof skeeG



Time Complexity: O(n) where n is size of the string

Auxiliary Space: O(n) where n is the size of string, which will be used in the form of function call stack of recursion.

Explanation: This problem can be expressed 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”


 

Please suggest if someone has a better solution which is more efficient in terms of space and time.
This article is contributed by Anurag Mishra and Aarti_Rathi .
 



Previous Article
Next Article

Similar Reads

Print Fibonacci Series in reverse order using Recursion
Given an integer N, the task is to print the first N terms of the Fibonacci series in reverse order using Recursion. Examples: Input: N = 5Output: 3 2 1 1 0Explanation: First five terms are - 0 1 1 2 3. Input: N = 10Output: 34 21 13 8 5 3 2 1 1 0 Approach: The idea is to use recursion in a way that keeps calling the same function again till N is gr
3 min read
Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
Reverse a Doubly linked list using recursion
Given a doubly linked list. Reverse it using recursion. Original Doubly linked list Reversed Doubly linked list We have discussed Iterative solution to reverse a Doubly Linked List Algorithm: If list is empty, return Reverse head by swapping head->prev and head->next If prev = NULL it means that list is fully reversed. Else reverse(head->p
9 min read
How to Reverse a Stack using Recursion
Write a program to reverse a stack using recursion, without using any loop. Example: Input: elements present in stack from top to bottom 1 2 3 4 Output: 4 3 2 1 Input: elements present in stack from top to bottom 1 2 3Output: 3 2 1 Recommended PracticeReverse a StackTry It!Reverse a stack using RecursionThe idea of the solution is to hold all value
11 min read
Reverse a linked list using recursion
Given a linked list, the task is to reverse the linked list by changing the links between nodes. Examples: Input: Linked List = 1 -> 2 -> 3 -> 4 -> NULL Output: 4 -> 3 -> 2 -> 1 -> NULL Input: Linked List = 1 -> 2 -> 3 -> 4 -> 5 -> NULL Output: 5 -> 4 -> 3 -> 2 -> 1 -> NULL Approach: To reverse
6 min read
Print alternate nodes of a linked list using recursion
Given a linked list, print alternate nodes of this linked list. Examples : Input : 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 Output : 1 -> 3 -> 5 -> 7 -> 9 Input : 10 -> 9 Output : 10 Recursive Approach : Initialize a static variable(say flag) If flag is odd print the node increase head and flag by 1,
6 min read
Programs to print Triangle and Diamond patterns using recursion
This article is aimed at giving a recursive implementation for pattern printing. Pattern 1: Example:Input: 5 Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *Implementation: C/C++ Code // Program to print the given pattern #include <iostream> using namespace std; void print_asterisk(int asterisk) { if (asterisk == 0) return;
15+ min read
Print even and odd numbers in a given range using recursion
Given two integers L and R, the task is to print all the even and odd numbers from L to R using recursion. Examples: Input: L = 1, R = 10Output: Even numbers: 2 4 6 8 10Odd numbers: 1 3 5 7 9 Input: L = 10, R = 25 Output: Even numbers:10 12 14 16 18 20 22 24 Odd numbers:11 13 15 17 19 21 23 25 Approach: Follow the steps below to solve the problem u
6 min read
Print root to leaf paths without using recursion
Given a binary tree, print all its root-to-leaf paths without using recursion. For example, consider the following Binary Tree. 6 / \ 3 5 / \ \ 2 5 4 / \ 7 4 There are 4 leaves, hence 4 root to leaf paths - 6->3->2 6->3->5->7 6->3->5->4 6->5>4 We strongly recommend you to minimize your browser and try this yourself fir
15+ min read
Print numbers 1 to N using Indirect recursion
Given a number N, we need to print numbers from 1 to N with out direct recursion, loops, labels. Basically we need to insert in above code snippet so that it can be able to print numbers from 1 to N? C/C++ Code #include <stdio.h> #define N 20; int main() { // Your code goes Here. } Examples : Input : 10 Output : 1 2 3 4 5 6 7 8 9 10 Input : 5
5 min read
Count of unique pairs (i, j) in an array such that sum of A[i] and reverse of A[j] is equal to sum of reverse of A[i] and A[j]
Given an array arr[] consisting of N positive integers, the task is to find the count of unique pairs (i, j) such that the sum of arr[i] and the reverse(arr[j]) is the same as the sum of reverse(arr[i]) and arr[j]. Examples: Input: arr[] = {2, 15, 11, 7}Output: 3Explanation:The pairs are (0, 2), (0, 3) and (2, 3). (0, 2): arr[0] + reverse(arr[2]) (
7 min read
Print reverse string after removing vowels
Given a string s, print reverse of string and remove the characters from the reversed string where there are vowels in the original string. Examples: Input : geeksforgeeksOutput : segrfsegExplanation :Reversed string is skeegrofskeeg, removing characters from indexes 1, 2, 6, 9 & 10 (0 based indexing),we get segrfseg .Input :duckOutput :kudA si
13 min read
Print words of a string in reverse order
Let there be a string say "I AM A GEEK". So, the output should be "GEEK A AM I" . This can done in many ways. One of the solutions is given in Reverse words in a string . Examples: Input : I AM A GEEK Output : GEEK A AM I Input : GfG IS THE BEST Output : BEST THE IS GfG This can be done in more simpler way by using the property of the "%s format sp
10 min read
Print 1 to 100 in C++ Without Loops and Recursion
We can print 1 to 100 without using loops and recursion using three approaches discussed below: 1) Template Metaprogramming: Templates in C++ allow non-datatypes also as parameters. Non-datatype means a value, not a datatype. Example: C/C++ Code // CPP Program to print 1 to 100 // without loops and recursion #include <iostream> using namespac
3 min read
Print ancestors of a given binary tree node without recursion
Given a Binary Tree and a key, write a function that prints all the ancestors of the key in the given binary tree.For example, consider the following Binary Tree 1 / \ 2 3 / \ / \ 4 5 6 7 / \ / 8 9 10 Following are different input keys and their ancestors in the above tree Input Key List of Ancestors ------------------------- 1 2 1 3 1 4 2 1 5 2 1
15 min read
Program for length of a string using recursion
Given a string calculate length of the string using recursion. Examples: Input : str = "abcd" Output :4 Input : str = "GEEKSFORGEEKS" Output :13 We have discussed 5 Different methods to find length of a string in C++ How to find length of a string without string.h and loop in C? Algorithm: recLen(str) { If str is NULL return 0 Else return 1 + recLe
3 min read
Convert a String to an Integer using Recursion
Given a string str representing a string, the task is to convert the given string into an integer.Examples: Input: str = "1234" Output: 1234Input: str = "0145" Output: 145 Approach: Write a recursive function that will take the first digit of the string and multiply it with the appropriate power of 10 and then add the recursive result for the subst
4 min read
Product of nodes at k-th level in a tree represented as string using Recursion
Prerequisite: Product of nodes at k-th level in a tree represented as stringGiven an integer ‘K’ and a binary tree in string format. Every node of a tree has value in range from 0 to 9. We need to find product of elements at K-th level from the root. The root is at level 0.Note: Tree is given in the form: (node value(left subtree)(right subtree))Ex
5 min read
Move all occurrence of letter 'x' from the string s to the end using Recursion
Given a string s, our task is to move all the occurrence of letter x to the end of the string s using recursion.Note: If there are only letter x in the given string then return the string unaltered. Examples: Input: s= "geekxsforgexxeksxx" Output: geeksforgeeksxxxxx Explanation: All occurrence of letter 'x' is moved to the end. Input: s = "xxxxx" O
8 min read
Decode a string recursively encoded as count followed by substring | Set 2 (using Recursion)
An encoded string str is given. The pattern in which the string is encoded is as follows. <count>[sub_str] ==> The substring 'sub_str' appears count times. The task is to decode this string str. Examples: Input: str = "1[b]"Output: bExplanation: The substring 'b' is repeated 1 time. Input: str = "2[ab]"Output: ababExplanation: The substrin
9 min read
Print Reverse a linked list using Stack
Given a linked list, print the reverse of it without modifying the list. Examples: Input : 1 2 3 4 5 6 Output : 6 5 4 3 2 1 Input : 12 23 34 45 56 67 78 Output : 78 67 56 45 34 23 12 Below are different solutions that are now allowed here as we cannot use extra space and modify the list. Recursive solution to print reverse a linked list. Requires e
9 min read
Print Strings In Reverse Dictionary Order Using Trie
Trie is an efficient information retrieval data structure. Using Trie, search complexities can be brought to an optimal limit. Given an array of strings. The task is to print all strings in reverse dictionary order using Trie. If there are duplicates in the input array, we need to print them only once. Examples: Input: str = {"cat", "there", "calle
12 min read
Decimal to Binary using recursion and without using power operator
Given an integer N, the task is convert and print the binary equaiva;ent of N.Examples: Input: N = 13 Output: 1101Input: N = 15 Output: 1111 Approach Write a recursive function that takes an argument N and recursively calls itself with the value N / 2 as the new argument and prints N % 2 after the call. The base condition will be when N = 0, simply
3 min read
Create a new string by alternately combining the characters of two halves of the string in reverse
Given a string s, create a new string such that it contains the characters of the two halves of the string s combined alternately in reverse order. Examples: Input : s = carbohydratesOutput : hsoebtraarcdy Input : s = sunshineOutput : sennuish Explanation: Example 1: Two halves of the string carbohydrate are carboh and ydrates. As they needed to be
7 min read
Check if a given string is a Reverse Bitonic String or not
Given a string str, the task is to check if that string is a Reverse Bitonic string or not. If the string str is reverse Bitonic string, then print "YES". Otherwise, print "NO". A Reverse Bitonic String is a string in which the characters are arranged in decreasing order followed by increasing order of their ASCII values. Examples: Input: str = "zy
6 min read
Maximize cost of repeated removal of string P or its reverse from the string S
Given two positive integers X and Y and two numeric strings S and P of length N and 2 respectively, the task is to find the maximum total cost obtained by repeatedly removing string P or the reverse of the string P from the string S at the cost of X and Y respectively. Examples: Input: S = "12333444", X = 5, Y = 4, P = "34"Output: 15Explanation:Bel
11 min read
Length of longest palindromic sub-string : Recursion
Given a string S, the task is to find the length longest sub-string which is a palindromeExamples: Input: S = "aaaabbaa" Output: 6 Explanation: Sub-string "aabbaa" is the longest palindromic sub-string.Input: S = "banana" Output: 5 Explanation: Sub-string "anana" is the longest palindromic sub-string. Approach:The idea is to use recursion to break
8 min read
Repeat substrings of the given String required number of times | Set 2 (Recursion)
Given string str, the task is to repeat every substring of the string X number of times where X is the number composed of the consecutive digits present just after the substring in the original string. For example, if str = “g1e2ks1” then the resultant string will be “geeks”. Examples: Input: str = “2a10bd3”Output: aaaaaaaaaabdbdbdExplanation: Firs
7 min read
Print Fibonacci Series in reverse order
Given a number n then print n terms of fibonacci series in reverse order. Examples: Input : n = 5 Output : 3 2 1 1 0 Input : n = 8 Output : 13 8 5 3 2 1 1 0 Algorithm 1) Declare an array of size n. 2) Initialize a[0] and a[1] to 0 and 1 respectively. 3) Run a loop from 2 to n-1 and store sum of a[i-2] and a[i-1] in a[i]. 4) Print the array in the r
4 min read
Print a matrix in Reverse Wave Form
Given a matrix, print it in Reverse Wave Form. Examples : Input : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output : 4 8 12 16 15 11 7 3 2 6 10 14 13 9 5 1 Input : 1 9 4 10 3 6 90 11 2 30 85 72 6 31 99 15 Output : 10 11 72 15 99 85 90 4 9 6 30 31 6 2 3 1 Approach :To get the reverse wave form for a given matrix, we first print the elements of the last
8 min read
Article Tags :
Practice Tags :