1. Extract, Reverse, and Re-insert
Intuition
First pass: collect all vowels into a vector vowels. Second pass: traverse s, whenever a vowel is encountered, pop the last vowel from vowels and replace the character in s.
When to apply: Basic baseline comparison.
Algorithm
- Initialize
vowels = []. - For
cins: ifisVowel(c):vowels.push(c). - Initialize
idx = vowels.length - 1. - Create mutable string
res. - For
ifrom 0 tos.length - 1: - If
isVowel(s[i]):res[i] = vowels[idx--]. - Else:
res[i] = s[i]. - Return
res.
Extract, Reverse, and Re-insert Trace
2 of 2 questions left todayObservation: Scan string and collect all vowels ('a','e','i','o','u' case-insensitive)
Observation: Scan string and collect all vowels ('a','e','i','o','u' case-insensitive).
Decision: Extracted array is ['e', 'o'].
Invariant: Original vowel order captured.
#include <iostream>#include <string>#include <vector>#include <unordered_set> class Solution { bool isVowel(char c) { c = tolower(c); return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; }public: std::string reverseVowels(std::string s) { std::vector<char> vowels; for (char c : s) { if (isVowel(c)) vowels.push_back(c); } int idx = vowels.size() - 1; for (char& c : s) { if (isVowel(c)) { c = vowels[idx--]; } } return s; }}; int main() { Solution sol; std::cout << sol.reverseVowels("IceCreAm") << std::endl; // AceCreIm std::cout << sol.reverseVowels("leetcode") << std::endl; // leotcede return 0;}Time & Space Complexity
- Time complexity:
O(N)— Two passes over string; stores up to N vowels in array. - Space complexity:
O(N)
Why Brute Force Doesn't Scale:
Two pointers skip consonants and swap vowels in-place.
Zero auxiliary memory overhead.