Two Pointers: Given a string, reverse the string by preserving whitespace.

Problem Statement:

You are given a string, reverse the string by preserving whitespace.

Example:

Input: s = Hi world
Output: dl rowih

Solution Explanation:

We will use two pointer approach to solve the problem.

Take 2 pointers start and end.

end will point to the start of the string. If the current char is not a space, then do end++.

else if its a space, add the substring of the char to the temp and reverse the temp.

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

Code Solution

#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
#include <algorithm>
#include <climits>
using namespace std;

string solution(string s) 
{
    string answer = "";
    int start = 0;
    int end = 0;
    int n = s.length();

    while(end < n)
    {
        if(s[end] != ' ')
        {
            end++;
        }
        else
        {
            string temp = s.substr(start, end - start);
            reverse(temp.begin(),temp.end());

            answer += temp;

            end++;

            start = end;
            answer += " ";
        }
    }

    string temp = s.substr(start, end - start);
    reverse(temp.begin(),temp.end());

    answer += temp;
    return answer;
}

int main()
{
    string s = "Hello World";
    cout << solution(s) << endl;
    return 0;
}

Output

olleH dlroW
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *