Problem Statement:
Given an array of characters reverse them in-place without taking extra space.
Example
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Solution
The solution is very simple.
Take 2 pointers, first pointer pointing to the start of the array.
second pointer pointing at the end of the array.
Then swap the elements and increase first pointer and decrement second pointer by 1.
Solution in C++
#include <vector>
#include <algorithm>
//visit www.ProDeveloperTutorial.com for 450+ solved questions
#include <iostream>
#include <string>
using namespace std;
string reverseString(string s)
{
int i = 0;
int j = s.size() - 1;
while(i < j)
{
swap(s[i++], s[j--]);
}
return s;
}
int main()
{
cout << "The reverse string is "<<reverseString("hello");
return 0;
}
Output:
The reverse string is olleh