Problem Statement: Given a String, reverse the string and print it.
Example 1: Input: str = "Takeuforward" Output: drawrofuekat Example 2: Input: str = "abcde" output: edcba
Solution:
Disclaimer: Don’t jump directly to the solution, try it out yourself first.
The most basic approach would be create a new empty string, iterate the above string from last to first element and copy it simultaneously to the new string.
What’s wrong with this approach?
It un-necessarily uses a new string, increasing the auxiliary space used in the entire process.
Can you think of any optimised approach?
Yes, if we can smartly use the Two Pointer Approach, we can reverse the string in-place without using any extra space.
Approach:
- Given a string
- Declare two variables(or pointers) i and j pointing to first and last index.
- Initialize i = 0 and j = n-1 where n is the length of the string.
- swap arr[i] and arr[j]
- keep increasing i = i + 1 and decreasing j = j -1 until i > j
- and print the reversed string
Code:
C Programs
#include<stdio.h>
void reversee(char arr[], int i, int j)
{
char temp;
while (i < j)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
int main()
{
char arr[] = "Takeuforward";
int n = 12;
printf("Original String is \n");
printf("%s\n",arr);
reversee(arr, 0, n-1);
printf("Reversed String is \n");
printf("%s ",arr);
return 0;
}
Output:
Original String is
Takeuforward
Reversed String is
drawrofuekaT
Time Complexity: O(n), where n is the length of the string
Space Complexity: O(1).
Special thanks to Subhrajit Das for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article