Reverse string without using any temporary variable

07 Jul, 2022
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.  
C++
Java
Python3
C#
Javascript
// C++ Program to reverse a string without// using temp variable#include <bits/stdc++.h>using namespace std;  // Function to reverse string and return reversed stringstring reversingString(string str, int start, int end){    // Iterate loop upto start not equal to end    while (start < end)    {        // XOR for swapping the variable        str[start] ^= str[end];        str[end] ^= str[start];        str[start] ^= str[end];          ++start;        --end;    }    return str;}  // Driver Codeint main(){    string s = "GeeksforGeeks";    cout << reversingString(s, 0, 12);    return 0;}
// Java Program to reverse a string without// using temp variableimport java.util.*;  class GFG {  // Function to reverse string and// return reversed stringstatic String reversingString(char []str,                               int start,                                int end){    // Iterate loop upto start not equal to end    while (start < end)    {        // XOR for swapping the variable        str[start] ^= str[end];        str[end] ^= str[start];        str[start] ^= str[end];          ++start;        --end;    }    return String.valueOf(str);}  // Driver Codepublic static void main(String[] args) {    String s = "GeeksforGeeks";    System.out.println(reversingString                      (s.toCharArray(), 0, 12));}}  // This code is contributed by 29AjayKumar
# Python3 Program to reverse a string # without using temp variable  # Function to reverse string and # return reversed stringdef reversingString(str, start, end):          # Iterate loop upto start not equal to end    while (start < end):          # XOR for swapping the variable        str = (str[:start] + chr(ord(str[start]) ^                                  ord(str[end])) +                                  str[start + 1:]);        str = (str[:end] + chr(ord(str[start]) ^                                ord(str[end])) +                                str[end + 1:]);        str = (str[:start] + chr(ord(str[start]) ^                                  ord(str[end])) +                                  str[start + 1:]);          start += 1;        end -= 1;    return str;  # Driver Codes = "GeeksforGeeks";print(reversingString(s, 0, 12));  # This code is contributed by 29AjayKumar
// C# Program to reverse a string without// using temp variableusing System;      class GFG {  // Function to reverse string and// return reversed stringstatic String reversingString(char []str,                              int start,                               int end){    // Iterate loop upto start     // not equal to end    while (start < end)    {        // XOR for swapping the variable        str[start] ^= str[end];        str[end] ^= str[start];        str[start] ^= str[end];          ++start;        --end;    }    return String.Join("", str);}  // Driver Codepublic static void Main(String[] args) {    String s = "GeeksforGeeks";    Console.WriteLine(reversingString                     (s.ToCharArray(), 0, 12));}}  // This code is contributed by 29AjayKumar
<script>  // Javascript program to reverse a string// without using temp variable  // Function to reverse string and// return reversed stringfunction reversingString(str, start, end){          // Iterate loop upto start not    // equal to end    while (start < end)    {                  // XOR for swapping the variable        str[start] = String.fromCharCode(            str[start].charCodeAt(0) ^             str[end].charCodeAt(0));        str[end] = String.fromCharCode(            str[end].charCodeAt(0) ^             str[start].charCodeAt(0));        str[start] = String.fromCharCode(            str[start].charCodeAt(0) ^             str[end].charCodeAt(0));                      ++start;        --end;    }    return(str).join("");}  // Driver Codelet s = "GeeksforGeeks";document.write(reversingString(    s.split(""), 0, 12));  // This code is contributed by rag2127  </script>
Output: 
skeeGrofskeeG
Time Complexity: O(n) Auxiliary Space: O(1)
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
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. 
C++
Java
Python3
C#
Javascript
// Reversing a string using reverse()#include<bits/stdc++.h>using namespace std;  int main(){   string str = "geeksforgeeks";         // Reverse str[begin..end]   reverse(str.begin(), str.end());         cout << str;   return 0;}
// Reversing a string using reverse()class GFG {public static void main(String[] args){    StringBuilder str = new StringBuilder("geeksforgeeks");          // Reverse str[begin..end]    str.reverse();    System.out.println(str);}}  // This code is contributed // by PrinciRaj1992
# Reversing a string using reverse()str = "geeksforgeeks";      # Reverse str[begin..end]str = "".join(reversed(str))      print(str);  # This code is contributed by 29AjayKumar
// Reversing a string using reverse()using System;using System.Linq;                   class GFG {public static void Main(String[] args){    String str = "geeksforgeeks";          // Reverse str[begin..end]    str = new string(str.Reverse().ToArray());    Console.WriteLine(str);}}  // This code is contributed by 29AjayKumar
<script>  // Reversing a string using reverse()      function reverseString(str) {        return str.split("").reverse().join("");    }          var str = ("geeksforgeeks");                document.write(reverseString(str));  // This code is contributed by todaysgaurav  </script>
Output: 
skeegrofskeeg
Time complexity : O(n) Auxiliary Space : O(1)
This article is contributed by Aarti_Rathi and Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
 
princiraj1992
29AjayKumar
todaysgaurav
rag2127
simmytarika5
adnanirshad158
a7977370173
codewithrathi
Bitwise-XOR
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
What is Data Structure: Types, Classifications and Applications
Print all the duplicates in the input string
Print all subsequences of a string
A Program to check if strings are rotations of each other or not
String class in Java | Set 1
Find if a string is interleaved of two other strings | DP-33
Remove first and last character of a string in Java
Find the smallest window in a string containing all characters of another string
Program to count occurrence of a given character in a string