Efficient C++ Code for Sorting Vowels in Linear Time with O(1) Space Complexity
Intuition\nThe task is to sort only the vowels in a given string while keeping all other characters in their original positions. This requires identifying vowel
# Intuition\nThe task is to sort only the vowels in a given string while keeping all other characters in their original positions. This requires identifying vowels, counting their occurrences, and then placing them back in a sorted manner.\n\n# Approach\n**Identify and Count Vowels**: Traverse the string to identify vowels and store their counts in an unordered map.\n\n**Sort Vowels:** Use a predefined list of vowels to maintain the sorted order. This list includes both uppercase and lowercase vowels.\n\n**Reconstruct the String:** Traverse the string again, replacing vowels with the sorted vowels in the order defined by the count in the unordered map.\n# Complexity\n- Time complexity:\nIdentifying and counting the vowels takes **O(n)** time, where n is the length of the string.\nReplacing the vowels based on their sorted order also takes O(n) time.\nOverall, the time complexity is **O(n)**.\n\n- Space complexity:\nThe unordered map for storing vowel counts requires O(1) space since there are a fixed number of vowels (10 in total: 5 uppercase and 5 lowercase).\nThe vector for storing the list of vowels also uses O(1) space.\nHence, the space complexity is **O(1)**.\n\n# Code\n```\nclass Solution {\npublic:\n    bool isVowel(char c){\n        if(c==\'A\'||c==\'E\'||c==\'I\'||c==\'O\'||c==\'U\'||c==\'a\'||c==\'e\'||c==\'i\'||c==\'o\'||c==\'u\')\n            return true;\n        return false;\n    }\n    string sortVowels(string s) {\n        vector<char> c = {\'A\',\'E\',\'I\',\'O\',\'U\',\'a\',\'e\',\'i\',\'o\',\'u\'};\n        unordered_map<char,int> mp;\n        for(auto x:s){\n            if(isVowel(x)) mp[x]++;\n        }\n        int p = 0;\n        for(int i=0;i<s.size();++i){\n            if(isVowel(s[i])) {\n                while(!mp[c[p]]){\n                    p++;\n                }\n                s[i] = c[p];\n                mp[c[p]]--;\n            }\n        }\n        return s;\n    }\n};\n```
['C++']