You are on page 1of 3

Different Methods to

reverse string in C++


Method 1 : Using Extra String

Here We just take last char from given string and add it to New
string. So new string will be reverse of given string. This is very
simple method to understand.

str = "Hello World";


string copied = "";
for(int i=str.size()-1; i>=0; i--) {
copied += str[i];
}
cout<<copied<<endl;

Complexity Analysis:
Time Complexity: O(N)
Space Complexity: O(N)

Method 2 : Using In-built Reverse Function


string str = "Hello World";
reverse(str.begin(),str.end());
cout<<str<<endl;

There is a direct function in the “algorithm” header file for doing


reverse that saves our time when programming.
Complexity Analysis:
Time Complexity: O(N)
Space Complexity: O(1)
Method 3 : Using Two Pointers Approach

str = "Hello World";


int l=0;
int r=str.size()-1;
while(l<r) {
char temp;
temp = str[l];
str[l] = str[r];
str[r] = temp;
l++;
r--;
}
cout<<str<<endl;

In Two pointer approach we assign first pointer l to 0th index of


string and second pointer r to the last index of string. Then we
simply swap this two pointer while l<r. We swap using temporary
variable temp.

Complexity Analysis:
Time Complexity: O(N)
Space Complexity: O(1)

Method 4 : Using Stack Data Structure

str = "Hello World";


stack<char> st;
for(int i=0; i<str.size(); i++) {
st.push(str[i]);
}
while(!st.empty()) {
cout<<st.top();
st.pop();
}

We know that Stack follows LIFO(Last in First out) rule. So we can


simple add char to stack and then pop out one by one and print it.
This will Reverse of the given string. Because first char of string will
pop out last.

Complexity Analysis:

Time Complexity: O(N)

Space Complexity: O(N) Because we take extra stack of space n.

Method 5 : Printing the string in reverse order

str = "Hello World";for(int i=str.size()-1; i>=0; i--) {


cout<<str[i];
}

If you just want to print the string in reverse order then you can use
this method. Just print char by char from last index ie. str.size()-1 to
first index ie. 0. But if you want to reverse actual string then you
need to use different approach.

You might also like