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

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.