Sort a string without altering the position of vowels

By | October 2, 2023

Given a string S of size N, the task is to sort the string without changing the place of vowels.

Examples:

Input: S = "example"
Output: elampxe
Explanation:
The consonants are xmpl. After sorting it becomes lmpx.
Now update the string after replacing each consonants with sorted consonants.

Input: S = "Cplusplus"
Output: Clluppsus

Recommended: Selection Sort

Approach:

To solve the above problem, follow the steps below:

  • Traverse the string S, copy all consonants of string S to another string say, temp.
  • Sort temp in alphabetical order.
  • Now again traverse the string S, and replace each consonant of string S with the temp[i], and increment i.

Below is the implementation of the above approach:

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;

// Function to sort the string without
// changing the place of vowels
void sortStr(string S)
{
    // Length of string S
    int N = S.size();

    string temp = "";
    // Traverse the string S
    for (int i = 0; i < N; i++) {
        if (S[i] != 'a' && S[i] != 'e' && S[i] != 'i'
            && S[i] != 'o' && S[i] != 'u')
            temp += S[i];
    }

    // Sort string temp
    if (temp.size())
        sort(temp.begin(), temp.end());

    // Pointing to starting index of temp
    int ptr = 0;

    // Traverse the string S
    for (int i = 0; i < N; i++) {
        if (S[i] != 'a' && S[i] != 'e' && S[i] != 'i'
            && S[i] != 'o' && S[i] != 'u')
            S[i] = temp[ptr++];
    }

    cout << S;
}

// Driver Code
int main()
{

    string S = "example";
    sortStr(S);
    return 0;
}

Output:

elampxe

Time Complexity: O(nlogn)
Auxiliary Space: O(n)

Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.