![]() |
VOOZH | about |
We are given a string. We are also given indexes of first and last characters in string. The task is to reverse the string without using any extra variable.
Examples:
Input : str = "abc" Output : str = "cba" Input : str = "GeeksforGeeks" Output : str = "skeeGrofskeeG"
If we take a look at program to reverse a string or array, all we need to do is swap two characters. The idea is to use XOR for swapping the variable. Below is the implementation of the idea.
Output:
skeeGrofskeeG
Time Complexity: O(n)
Auxiliary Space: O(1)
If we are allowed to library function, we can also use the idea discussed in quickly reverse a string in C++. We don't even need indexes of first and last characters.
Output:
skeegrofskeeg
Time complexity : O(n)
Auxiliary Space : O(1)
This article is contributed by Aarti_Rathi and Mr. Somesh Awasthi.