Reverse string without temporary variable

Write a function to reverse a string without using extra variable.

Example

Input string : “tutorial-cup”

Output : “puc-lairotut”

Time complexity : O(n)

Algorithm

1. Store start index in low and end index in high.

2. Here, without creating a temp variable to swap characters, we use xor(^).

3. Traverse the input string.

4. Swap from first variable to end using xor.

5. Return the final output string.

C++ Program

#include <bits/stdc++.h>

using namespace std;
 
string Reverse(string input_string, int low, int high)
{
    //Traverse the entire string
    while (low < high)
    {
        //swap start and end using xor
        input_string[low] ^= input_string[high];
        input_string[high] ^= input_string[low];
        input_string[low] ^= input_string[high];
 
        low = low + 1;
        high = high -1;
    }
    return input_string;
}
 
//main function
int main()
{
    string Input_string = "tutorial-cup";
    cout<<"Output: "<<Reverse(Input_string, 0, 11);
    return 0;
}
Try It

 


Next > < Prev
Scroll to Top