C Program to Reverse a String Using Recursion
Reversing a string means changing the order of characters in the string so that the last character becomes the first character of the string.
Example:
Input: Geeks
Output: skeeG
Input: Hello
Output: olleH
Simple Approach
Below is the C program to reverse a string using recursion:
C
# include <stdio.h>
void reverse( char *str)
{
if (*str)
{
reverse(str + 1);
printf ( "%c" , *str);
}
}
int main()
{
char a[] = "Geeks for Geeks" ;
reverse(a);
return 0;
}
|
Explanation of the above method
- The recursive function (reverse) takes the string pointer (str) as input and calls itself with the next location to the 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.
The complexity of the method above
Time Complexity: O(n^2) as substr() method has a time complexity of O(k) where k is the size of the returned string.
So for every recursive call, we are reducing the size of the string by one, which leads to a series like (k-1)+(k-2)+…+1 = k*(k-1)/2 = O(k^2) = O(n^2)
See Reverse a string for other methods to reverse a string.
Auxiliary Space: O(n)
Efficient Approach
We can store each character in the recursive stack and then can print while coming back as shown in the below code:
C
#include <stdio.h>
void reverse( char *str, int index,
int n)
{
if (index == n)
return ;
char temp = str[index];
reverse(str, index + 1, n);
printf ( "%c" , temp);
}
int main()
{
char a[] = "Geeks for Geeks" ;
int n = sizeof (a) / sizeof (a[0]);
reverse(a, 0, n);
return 0;
}
|
Output
skeeG roF skeeG
The Complexity of the method above
Time Complexity: O(n) where n is the size of the string
Auxiliary Space: O(n) where n is the size of the string, which will be used in the form of a function call stack of recursion.
Last Updated :
19 Jun, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...