Home » Interview Questions » String Interview Questions » Reverse string without temporary variable

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

 

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote Count

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

READ  Regular Expression Matching
Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions