Two Pointers: Given a string with special characters, reverse only alphabets

Problem Statement:

Given a string with special characters, reverse only alphabets

Example:

Input: str = ab$cd
Output: str = dc$ba

Solution Explanation:

We will solve the problem using two pointers approach.

Take left pointer at the starting of the string and right pointer at the end of the string.

Then move left forward until it finds an alphabet

Then move right backward until it finds an alphabet

Swap both pointers, and stop the iteration when left and right pointer meet

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

Code Solution

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

void solution(string s) 
{
    int left = 0, right = s.size() - 1;

    while (left < right)
    {
        if (!isalpha(s[left]))
            left++; 
        else if (!isalpha(s[right]))
            right--; 
        else 
            swap(s[left++], s[right--]);
    }
    cout<< s;
}

int main()
{
    string s = "ab$cd";
    solution(s);
    return 0;
}

Output

dc$ba
Write a Comment

Leave a Comment

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