{"id":"reverse-vowels-of-a-string","title":"Reverse Vowels of a String","difficulty":"easy","patterns":["two-pointers"],"primaryConcept":"array-two-pointers-basics","concepts":["array-two-pointers-basics"],"problemForm":"intro","companies":["Google","Amazon","Meta"],"category":"arrays-strings","executionStyle":"solution-method","compareMode":"exact","description":"Given a string `s`, reverse only the vowels in the string and return the resulting string. The vowels are `a`, `e`, `i`, `o`, and `u`, and they may appear in either uppercase or lowercase.","examples":[{"input":"s = \"IceCreAm\"","output":"\"AceCreIm\"","explanation":"The vowels are I, e, e, and A. Reversing only those vowels gives A, e, e, and I."},{"input":"s = \"leetcode\"","output":"\"leotcede\"","explanation":"Only the vowel positions change; the consonants stay fixed."},{"input":"s = \"rhythm\"","output":"\"rhythm\"","explanation":"There are no vowels to reverse."}],"constraints":[{"id":"1-len-s-3-10-5","text":"1 <= len(s) <= 3 * 10^5","check":{"kind":"sizeRange","target":"s","measure":"stringLength","min":1,"max":300000}},{"id":"s-consists-of-printable-ascii-characters","text":"s consists of printable ASCII characters."}],"starterCode":"class Solution:\n    def reverseVowels(self, s: str) -> str:\n        # Your code here\n        pass","functionName":"reverseVowels","testCases":[{"id":"1","input":{"s":"IceCreAm"},"expected":"AceCreIm","description":"Mixed case vowels from the prompt."},{"id":"2","input":{"s":"leetcode"},"expected":"leotcede","description":"Multiple repeated vowels."},{"id":"3","input":{"s":"hello"},"expected":"holle","description":"Two vowels swap places."},{"id":"4","input":{"s":"aA"},"expected":"Aa","description":"Uppercase and lowercase vowels both count."},{"id":"5","input":{"s":"rhythm"},"expected":"rhythm","description":"No vowels means the string is unchanged."},{"id":"6","input":{"s":".,aE!"},"expected":".,Ea!","description":"Punctuation is skipped and stays in place."},{"id":"h1","input":{"s":"Design"},"expected":"Disegn","description":"One lowercase pair inside the word swaps."},{"id":"h2","input":{"s":"AEIOU"},"expected":"UOIEA","description":"All characters are uppercase vowels."},{"id":"h3","input":{"s":"bcdfg"},"expected":"bcdfg","description":"All consonants stay unchanged."},{"id":"h4","input":{"s":"Ab,cde!O"},"expected":"Ob,cde!A","description":"Vowels swap across punctuation."}],"hints":[{"level":1,"content":"Only vowels move; every other character keeps its index.","revealPattern":false},{"level":2,"content":"Use two pointers from the ends and skip inward until both pointers land on vowels.","revealPattern":true},{"level":3,"content":"Convert the string to a mutable list, swap the two vowel characters, then join the list at the end.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach gives the best balance of clarity and efficiency?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"collect-vowels","name":"Collect vowels, then write back","summary":"Scan once to collect vowels, then scan again to place them in reverse order.","decisionReason":"It builds a second list of vowels and walks the string twice; the swap can do the same reversal in place.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Runs in O(n) time and uses O(n) space."],"isOptimal":false},{"id":"two-pointer-swap","name":"Two-pointer vowel swaps","summary":"Use two pointers to find the next left and right vowels, swap them, and continue inward.","decisionReason":"Two pointers skip to the outermost remaining vowels and swap them, reversing the vowels in one pass without a side list.","complexity":{"time":"O(n)","space":"O(1)"},"tradeoffs":["One pass, swaps in place, no extra vowel list."],"isOptimal":true},{"id":"nested-search","name":"Search for a matching vowel each time","summary":"For each vowel, scan from the other side to find its partner.","decisionReason":"Re-scanning from the far end for each vowel turns one pass into quadratic work on a string that is mostly vowels.","complexity":{"time":"O(n^2)","space":"O(n)"},"tradeoffs":["Runs in O(n^2) time and uses O(n) space."],"isOptimal":false}]},"codingCheckpoints":[{"id":"build-vowel-set","title":"Build vowel membership state","description":"Create a reusable set or equivalent membership test for all lowercase and uppercase vowels.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"set-membership","fact":"initializes_set_state","scope":"convert-to-set","readMode":"set-membership-value-query-v1"}]},"commonMistakes":["Only including lowercase vowels","Checking vowels with repeated string scans instead of reusable membership state"],"hint":"Put all ten vowel characters into a set-like structure.","semanticSpec":{"intent":"Initialize reusable vowel membership state.","doneWhen":"The code creates a set-like membership structure for vowel checks before the pointer loop.","shouldFailWhen":"This step should fail if vowel membership is not represented as reusable state.","roles":["vowel membership state"],"mustProve":["The solution initializes set-like vowel membership state."],"mustNotAccept":["Repeated ad hoc string scans without reusable membership state."],"proofSnippets":[{"id":"py-reverse-vowels-build-vowel-set","language":"python","code":"class Solution:\n    def reverseVowels(self, s: str) -> str:\n        vowels = set('aeiouAEIOU')"}]}},{"id":"init-pointers","title":"Initialize boundary pointers","description":"Start one pointer at the first character and the other at the last character.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"initializes_boundary_pointers","scope":"init-pointers","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Setting the right pointer to the string length instead of the last index","Starting both pointers at the same side"],"hint":"Use the inclusive first and last valid indices.","semanticSpec":{"intent":"Initialize boundary pointers over the mutable character sequence.","doneWhen":"One pointer starts at the first character and the other starts at the final valid character index.","shouldFailWhen":"This step should fail if either pointer is missing, starts on the wrong side, or uses an invalid upper bound.","roles":["left boundary pointer","right boundary pointer","character sequence"],"mustProve":["The left pointer starts at the first index.","The right pointer starts at the final valid index."],"mustNotAccept":["A right pointer initialized to the sequence length.","Both pointers starting from the same side."],"proofSnippets":[{"id":"py-reverse-vowels-init-pointers","language":"python","code":"class Solution:\n    def reverseVowels(self, s: str) -> str:\n        chars = list(s)\n        vowels = set('aeiouAEIOU')\n        left = 0\n        right = len(chars) - 1"}]}},{"id":"main-loop","title":"Loop while pointers are apart","description":"Continue until the left and right pointers meet or cross.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"loops_while_pointers_apart","scope":"main-loop","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Using a loop that can keep running after the pointers cross","Scanning with only one pointer"],"hint":"The outer loop should be guarded by left being strictly before right.","semanticSpec":{"intent":"Loop while the vowel-search boundary pointers are still apart.","doneWhen":"The outer loop guard compares the left and right boundary pointers.","shouldFailWhen":"This step should fail if the loop ignores either pointer or keeps running after they meet.","roles":["left boundary pointer","right boundary pointer","outer loop guard"],"mustProve":["The loop condition uses both boundary pointers."],"mustNotAccept":["A one-pointer scan as the main reversal loop.","A loop that can continue after the pointers cross."],"proofSnippets":[{"id":"py-reverse-vowels-main-loop","language":"python","code":"class Solution:\n    def reverseVowels(self, s: str) -> str:\n        chars = list(s)\n        vowels = set('aeiouAEIOU')\n        left = 0\n        right = len(chars) - 1\n        while left < right:\n            pass"}]}},{"id":"skip-left","title":"Skip non-vowels from the left","description":"Move the left pointer forward until it lands on a vowel or reaches the right pointer.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"skips_left_until_boundary_filter_match","scope":"skip-left","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Moving left without checking vowel membership","Forgetting to keep left before right while skipping"],"hint":"Advance left while the current character is not a vowel.","semanticSpec":{"intent":"Advance the left pointer past non-vowels.","doneWhen":"Inside the outer loop, the left pointer moves right while its current character fails the vowel-membership test.","shouldFailWhen":"This step should fail if left advances without checking vowel membership or ignores the right boundary.","roles":["left boundary pointer","right boundary pointer","vowel membership state"],"mustProve":["The left pointer skip is guarded by vowel membership.","The skip preserves the left-before-right boundary."],"mustNotAccept":["Advancing left unconditionally.","Skipping based on a non-vowel-unrelated predicate."],"proofSnippets":[{"id":"py-reverse-vowels-skip-left","language":"python","code":"class Solution:\n    def reverseVowels(self, s: str) -> str:\n        chars = list(s)\n        vowels = set('aeiouAEIOU')\n        left = 0\n        right = len(chars) - 1\n        while left < right:\n            while left < right and chars[left] not in vowels:\n                left += 1"}]}},{"id":"skip-right","title":"Skip non-vowels from the right","description":"Move the right pointer backward until it lands on a vowel or reaches the left pointer.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"skips_right_until_boundary_filter_match","scope":"skip-right","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Moving right in the wrong direction","Skipping only lowercase vowels"],"hint":"Retreat right while the current character is not a vowel.","semanticSpec":{"intent":"Retreat the right pointer past non-vowels.","doneWhen":"Inside the outer loop, the right pointer moves left while its current character fails the vowel-membership test.","shouldFailWhen":"This step should fail if right retreats without checking vowel membership or ignores the left boundary.","roles":["left boundary pointer","right boundary pointer","vowel membership state"],"mustProve":["The right pointer skip is guarded by vowel membership.","The skip preserves the left-before-right boundary."],"mustNotAccept":["Retreating right unconditionally.","Skipping only one vowel case."],"proofSnippets":[{"id":"py-reverse-vowels-skip-right","language":"python","code":"class Solution:\n    def reverseVowels(self, s: str) -> str:\n        chars = list(s)\n        vowels = set('aeiouAEIOU')\n        left = 0\n        right = len(chars) - 1\n        while left < right:\n            while left < right and chars[left] not in vowels:\n                left += 1\n            while left < right and chars[right] not in vowels:\n                right -= 1"}]}},{"id":"swap-and-advance","title":"Swap vowels and move inward","description":"When both pointers are on vowels, swap those characters and then move both pointers inward.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"swaps_boundary_values","scope":"swap-values","readMode":"two-pointer-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"moves_boundary_pointers_inward","scope":"move-pointers","readMode":"two-pointer-value-query-v1"}]}]},"commonMistakes":["Swapping characters before both pointers land on vowels","Forgetting to advance both pointers after a swap"],"hint":"Swap the two boundary entries, then move left forward and right backward.","semanticSpec":{"intent":"Swap the two selected vowels and move both pointers inward.","doneWhen":"After the skip loops, the code swaps the boundary characters and advances both pointers inward.","shouldFailWhen":"This step should fail if the code only swaps, only moves, or swaps before the boundary positions are selected.","roles":["character sequence","left boundary pointer","right boundary pointer"],"mustProve":["The selected boundary values are swapped.","Both boundary pointers move inward after the swap."],"mustNotAccept":["Moving pointers without swapping the selected vowels.","Swapping unrelated positions."],"proofSnippets":[{"id":"py-reverse-vowels-swap-and-advance","language":"python","code":"class Solution:\n    def reverseVowels(self, s: str) -> str:\n        chars = list(s)\n        vowels = set('aeiouAEIOU')\n        left = 0\n        right = len(chars) - 1\n        while left < right:\n            while left < right and chars[left] not in vowels:\n                left += 1\n            while left < right and chars[right] not in vowels:\n                right -= 1\n            if left < right:\n                chars[left], chars[right] = chars[right], chars[left]\n                left += 1\n                right -= 1"}]}},{"id":"return-string","title":"Return the rebuilt string","description":"Return the mutated character list as a string.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"returns_mutated_boundary_sequence","scope":"return-sequence","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Returning the character list instead of a string","Returning the original string after mutating a copy"],"hint":"Join the mutable characters back into one string.","semanticSpec":{"intent":"Return a string derived from the mutated character sequence.","doneWhen":"After the pointer loop, the code returns the boundary-mutated character sequence rebuilt as a string.","shouldFailWhen":"This step should fail if the return ignores the mutated character sequence.","roles":["mutated character sequence","return string"],"mustProve":["The return occurs after the swap loop.","The returned value is derived from the mutated character sequence."],"mustNotAccept":["Returning the original input string.","Returning an unrelated string."],"proofSnippets":[{"id":"py-reverse-vowels-return-string","language":"python","code":"class Solution:\n    def reverseVowels(self, s: str) -> str:\n        chars = list(s)\n        vowels = set('aeiouAEIOU')\n        left = 0\n        right = len(chars) - 1\n        while left < right:\n            while left < right and chars[left] not in vowels:\n                left += 1\n            while left < right and chars[right] not in vowels:\n                right -= 1\n            if left < right:\n                chars[left], chars[right] = chars[right], chars[left]\n                left += 1\n                right -= 1\n        return ''.join(chars)"}]}}],"slides":[{"id":"read-the-problem","chapter":"The problem","kind":"info","eyebrow":"Read the problem","title":"Reverse only the vowels, leave the rest","workspacePanel":"problem","body":["You get a string and must reverse the order of just its vowels (a, e, i, o, u, upper or lower case). Every other character stays exactly where it is.","The first instinct is to pull the vowels out, reverse them, and write them back. Follow that idea next, and notice what it costs."]},{"id":"brute-force","chapter":"The problem","kind":"code-trace","eyebrow":"The obvious way","title":"Pull the vowels out, reverse, write them back","summary":"Collecting the vowels, reversing them, and writing them back gets the right answer, but it keeps a full second copy of the vowels. Watch how that side list grows with the input.","workspacePanel":"trace","body":["Scan once to collect the vowels, reverse that side list, then scan again and drop them back into the vowel slots."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"chars = list(s)\ncollected = []\nfor c in chars:\n    if is_vowel(c):\n        collected.append(c)\ncollected.reverse()\nwrite = 0\nfor i in range(len(chars)):\n    if is_vowel(chars[i]):\n        chars[i] = collected[write]\n        write += 1\nreturn chars","typeContext":{"externalFunctions":{"is_vowel":{"params":["char"],"returns":"bool"}}},"steps":[{"id":"collect","title":"First walk: copy every vowel into a side list","codeLine":5,"summary":"Scan \"favorite\" left to right and copy each vowel out: a, then o, then i, then e. The side list now holds [a, o, i, e], a full second copy of the vowels.","state":{"s":"favorite","i":7,"arrays":[{"name":"collected","values":["a","o","i","e"]}]}},{"id":"reverse-list","title":"Reverse the side list","codeLine":6,"summary":"Reverse the collected vowels in place: [a, o, i, e] becomes [e, i, o, a]. That is the order they must be written back in.","state":{"s":"favorite","arrays":[{"name":"collected","values":["e","i","o","a"]}]}},{"id":"write-back","title":"Second walk: drop the reversed vowels back in","codeLine":10,"summary":"Scan again. At each vowel slot take the next character from the reversed list: index 1 gets e, index 3 gets i, index 5 gets o, index 7 gets a. The result is \"fevirota\".","state":{"s":"fevirota","i":7,"arrays":[{"name":"collected","values":["e","i","o","a"]}]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const chars = Array.from(s);\nconst collected = [];\nfor (const c of chars) {\n    if (isVowel(c)) {\n        collected.push(c);\n    }\n}\ncollected.reverse();\nlet write = 0;\nfor (let i = 0; i < chars.length; i++) {\n    if (isVowel(chars[i])) {\n        chars[i] = collected[write];\n        write++;\n    }\n}\nreturn chars.join(\"\");","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8,"7":9,"8":10,"9":11,"10":12,"11":13,"12":16},"statementBundles":{"5":{"startLine":5,"endLine":7},"11":{"startLine":13,"endLine":15}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const chars = Array.from(s);\nconst collected: Array<string> = [];\nfor (const c of chars) {\n    if (isVowel(c)) {\n        collected.push(c);\n    }\n}\ncollected.reverse();\nlet write = 0;\nfor (let i = 0; i < chars.length; i++) {\n    if (isVowel(chars[i])) {\n        chars[i] = collected[write];\n        write++;\n    }\n}\nreturn chars.join(\"\");","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8,"7":9,"8":10,"9":11,"10":12,"11":13,"12":16},"statementBundles":{"5":{"startLine":5,"endLine":7},"11":{"startLine":13,"endLine":15}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Character> chars = new ArrayList<Character>(String.valueOf(s).chars().mapToObj(ch -> (char)ch).collect(java.util.stream.Collectors.toList()));\nList<Character> collected = new ArrayList<>();\nfor (Character c : chars) {\n    if (isVowel(c)) {\n        collected.add(c);\n    }\n}\nCollections.reverse(collected);\nint write = 0;\nfor (int i = 0; i < chars.size(); i++) {\n    if (isVowel(chars.get(i))) {\n        chars.set(i, collected.get(write));\n        write++;\n    }\n}\nreturn chars.stream().map(String::valueOf).collect(java.util.stream.Collectors.joining());","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8,"7":9,"8":10,"9":11,"10":12,"11":13,"12":16},"statementBundles":{"5":{"startLine":5,"endLine":7},"11":{"startLine":13,"endLine":15}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<string> chars = s.Select(ch => ch.ToString()).ToList();\nList<string> collected = new();\nforeach (string c in chars) {\n    if (IsVowel(c)) {\n        collected.Add(c);\n    }\n}\ncollected.Reverse();\nint write = 0;\nfor (int i = 0; i < chars.Count; i++) {\n    if (IsVowel(chars[i])) {\n        chars[i] = collected[write];\n        write++;\n    }\n}\nreturn string.Concat(chars);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8,"7":9,"8":10,"9":11,"10":12,"11":13,"12":16},"statementBundles":{"5":{"startLine":5,"endLine":7},"11":{"startLine":13,"endLine":15}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"string chars = s;\nstring collected;\nfor (char c : chars) {\n    if (is_vowel(c)) {\n        collected.push_back(c);\n    }\n}\nreverse(collected.begin(), collected.end());\nint write = 0;\nfor (int i = 0; i < chars.size(); i++) {\n    if (is_vowel(chars[i])) {\n        chars[i] = collected[write];\n        write++;\n    }\n}\nreturn chars;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":8,"7":9,"8":10,"9":11,"10":12,"11":13,"12":16},"statementBundles":{"5":{"startLine":5,"endLine":7},"11":{"startLine":13,"endLine":15}}}}}},{"id":"brute-cost","chapter":"The problem","kind":"case-probe","eyebrow":"Count the cost","title":"What grows with the number of vowels in the string?","workspacePanel":"trace","summary":"The side list holds one entry per vowel, and the string is walked twice.","options":[{"id":"extra-storage","label":"Extra storage: the side list keeps a full copy of every vowel","rationale":"A string that is all vowels makes the side list as long as the string itself, so the memory used grows right alongside the input.","isCorrect":true},{"id":"nothing-extra","label":"Nothing extra: it reuses the characters already in the string","rationale":"The collected list is a second copy built before any write-back. The more vowels there are, the more characters it holds.","isCorrect":false},{"id":"number-of-walks","label":"The number of walks: more vowels means more passes over the string","rationale":"The code always makes one collect pass and one write-back pass. More vowels increase the side list.","isCorrect":false}],"answer":"The side list grows with the vowel count. On a string of all vowels it is a second copy as long as the input, so this naive approach spends extra space the swap will not need."},{"id":"pairing-probe","chapter":"The idea","kind":"case-probe","eyebrow":"Find the move","title":"After reversing the vowel list, where does each vowel land?","workspacePanel":"visualizer","summary":"The vowels in order are a, o, i, e; reversed they are e, i, o, a.","options":[{"id":"swaps-mirror","label":"Each vowel trades places with the vowel the same distance in from the other end","rationale":"Reversing sends the first vowel to the last slot and the last to the first, the second to the second-last, and so on; every vowel just swaps with its mirror partner.","isCorrect":true},{"id":"shifts-one","label":"Each vowel shifts one position toward the front","rationale":"A reversal is not a rotation. The first and last vowels trade ends; nothing slides by a single step.","isCorrect":false},{"id":"only-ends","label":"Only the first and last vowels move; the middle ones stay","rationale":"The second vowel goes to the second-from-last slot too. Every vowel moves to its mirror position.","isCorrect":false}],"answer":"Reversing pairs the outermost vowels and works inward: a trades with e, and the inner o trades with i. The side list was never doing more than swapping mirror pairs.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"pairing-state","state":{"s":"favorite","left":1,"right":7}}]}},{"id":"skip-invariant","chapter":"The idea","kind":"case-probe","eyebrow":"Name the rule","title":"A pointer lands on a consonant. What should it do?","workspacePanel":"visualizer","summary":"The left pointer starts at index 0 on \"f\", a consonant, while the right pointer rests on a vowel.","options":[{"id":"skip-to-vowel","label":"Step inward, past every consonant, until it reaches a vowel","rationale":"Consonants never move, so a pointer parked on one has nothing to swap; it must keep stepping inward until it finds the next vowel to pair.","isCorrect":true},{"id":"swap-anyway","label":"Swap the consonant with the waiting vowel","rationale":"That would move a consonant out of its slot, and the rules fix every consonant in place. A consonant is never a swap partner.","isCorrect":false},{"id":"stop-loop","label":"Stop; a consonant at the boundary means there is nothing left to reverse","rationale":"There may be vowels further in. One consonant at the boundary only means this pointer must move past it, not that the work is done.","isCorrect":false}],"answer":"A pointer on a consonant keeps stepping inward until it lands on a vowel. Both pointers must be on vowels before a swap can happen.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"skip-state","state":{"s":"favorite","left":0,"right":7}}]}},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Swap mirror pairs in place, or build a reversed list first?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"s":"fevorita","left":2,"right":6}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Two pointers at the ends, closing in","workspacePanel":"visualizer","body":["Start one pointer at index 0 and the other at index 7. Each round does the same thing: step each pointer inward until it sits on a vowel, swap those two vowels, then move both pointers one step further in.","When the pointers meet or cross, every vowel pair has been swapped and the string is done."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"s":"favorite","left":0,"right":7}}]}},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the swaps","title":"Trace the two-pointer reversal","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"skip-left","state":{"s":"favorite","left":0,"right":7}},{"id":"first-swap","state":{"s":"favorite","left":1,"right":7}},{"id":"second-swap","state":{"s":"fevirota","left":4,"right":4}}]},"beats":[{"id":"skip-left","title":"Where does the left pointer stop?","summary":"Right is on \"e\" at index 7, already a vowel. Left starts at index 0 on \"f\".","prompt":"Left begins at index 0, on the consonant \"f\".","options":[{"id":"land-1","label":"Index 1, on \"a\"","rationale":"\"f\" is a consonant, so left steps inward once and lands on \"a\", the first vowel from the front.","isCorrect":true},{"id":"stay-0","label":"Index 0, on \"f\"","rationale":"\"f\" is not a vowel, so the pointer cannot stop there; it must move past it.","isCorrect":false},{"id":"land-3","label":"Index 3, on \"o\"","rationale":"\"a\" at index 1 is already a vowel, so left stops there and never reaches index 3 this round.","isCorrect":false}],"answer":"Left skips \"f\" and stops at \"a\" on index 1. Right is already on the vowel \"e\"."},{"id":"first-swap","title":"Both pointers have stopped on vowels. Which characters move?","summary":"Left is on \"a\" at 1 and right is on \"e\" at 7.","prompt":"Left holds \"a\", right holds \"e\".","options":[{"id":"swap-ae","label":"Swap \"a\" and \"e\", making \"fevorita\", then step both pointers inward","rationale":"The outer vowel pair trades places, then left moves to 2 and right to 6 to look for the next pair.","isCorrect":true},{"id":"move-only","label":"Move both pointers inward without swapping","rationale":"Both pointers sit on vowels, so this is exactly the moment to swap; skipping the swap loses the reversal.","isCorrect":false},{"id":"swap-no-move","label":"Swap \"a\" and \"e\" but leave the pointers where they are","rationale":"Without stepping inward the same two vowels would be swapped again, undoing the work.","isCorrect":false}],"answer":"Swap gives \"fevorita\". Then left advances to 2 and right retreats to 6."},{"id":"second-swap","title":"After the inner pair swaps, what string is returned?","summary":"From \"fevorita\", left skipped \"v\" to reach \"o\" at index 3; right skipped \"t\" to reach \"i\" at index 5.","prompt":"Left holds \"o\", right holds \"i\"; once they swap, left would pass right.","options":[{"id":"return-fevirota","label":"\"fevirota\"","rationale":"Swapping \"o\" and \"i\" turns \"fevorita\" into \"fevirota\", the pointers cross, and that string is returned.","isCorrect":true},{"id":"return-fevorita","label":"\"fevorita\"","rationale":"That is the string before the inner swap. The o and i still have to trade places, which changes index 3 and index 5.","isCorrect":false},{"id":"return-favorite","label":"\"favorite\"","rationale":"The first swap already turned a and e around; that change stays in the returned string.","isCorrect":false}],"answer":"Swapping \"o\" and \"i\" gives \"fevirota\", the pointers cross, and \"fevirota\" is returned."}]},{"id":"skip-once-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Could a single check be enough to find the next vowel?","summary":"Stepping a pointer past a consonant with one if-check looks close to the repeated rule: if the character is not a vowel, move once, then carry on. It passes any string whose vowels are one step apart. Watch it on a denser consonant stretch.","workspacePanel":"trace","pitfall":"The code below advances the left pointer with a single if instead of skipping every consonant in a row.","whyItMatters":"Skipping must stay in a loop while the pointer is on a consonant. A single if stops one short on back-to-back consonants and swaps a fixed character out of place.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"chars = list(s)\nleft = 0\nright = len(chars) - 1\nif not is_vowel(chars[left]):\n    left += 1\nleft_char = chars[left]\nchars[left] = chars[right]\nchars[right] = left_char","typeContext":{"externalFunctions":{"is_vowel":{"params":["char"],"returns":"bool"}}},"steps":[{"id":"start","title":"Pointers at the ends","codeLine":2,"summary":"s = \"byoi\". Left starts at index 0 on \"b\"; right is on the vowel \"i\" at index 3.","state":{"s":"byoi","left":0,"right":3}},{"id":"single-step","title":"One step lands on another consonant","codeLine":5,"summary":"\"b\" is not a vowel, so left moves once to index 1. But index 1 is \"y\", still a consonant.","state":{"s":"byoi","left":1,"right":3}},{"id":"wrong-write","title":"It overwrites a consonant slot","codeLine":7,"summary":"left is on \"y\", a consonant. The swap copies \"i\" into index 1, where \"y\" sat.","state":{"s":"bioi","left":1,"right":3}},{"id":"broken","title":"A consonant moved","codeLine":8,"summary":"Finishing the swap writes \"y\" into index 3, giving \"bioy\". The correct answer is \"byio\": only o and i should have traded.","state":{"s":"bioy","left":1,"right":3}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const chars = Array.from(s);\nlet left = 0;\nconst right = chars.length - 1;\nif (!isVowel(chars[left])) {\n    left++;\n}\nconst leftChar = chars[left];\nchars[left] = chars[right];\nchars[right] = leftChar;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9},"statementBundles":{"5":{"startLine":5,"endLine":6}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const chars = Array.from(s);\nlet left = 0;\nconst right = chars.length - 1;\nif (!isVowel(chars[left])) {\n    left++;\n}\nconst leftChar = chars[left];\nchars[left] = chars[right];\nchars[right] = leftChar;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9},"statementBundles":{"5":{"startLine":5,"endLine":6}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Character> chars = new ArrayList<Character>(String.valueOf(s).chars().mapToObj(ch -> (char)ch).collect(java.util.stream.Collectors.toList()));\nint left = 0;\nint right = chars.size() - 1;\nif (!isVowel(chars.get(left))) {\n    left++;\n}\nchar leftChar = String.valueOf(chars.get(left)).charAt(0);\nchars.set(left, chars.get(right));\nchars.set(right, leftChar);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9},"statementBundles":{"5":{"startLine":5,"endLine":6}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<string> chars = s.Select(ch => ch.ToString()).ToList();\nint left = 0;\nint right = chars.Count - 1;\nif (!IsVowel(chars[left])) {\n    left++;\n}\nstring leftChar = chars[left];\nchars[left] = chars[right];\nchars[right] = leftChar;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9},"statementBundles":{"5":{"startLine":5,"endLine":6}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"string chars = s;\nint left = 0;\nint right = chars.size() - 1;\nif (!is_vowel(chars[left])) {\n    left++;\n}\nchar left_char = chars[left];\nchars[left] = chars[right];\nchars[right] = left_char;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9},"statementBundles":{"5":{"startLine":5,"endLine":6}}}}}},{"id":"edge-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","summary":"The swap is safe now: both pointers reach a vowel before trading, and a run of consonants no longer fools them.","ctaLabel":"Check edge cases","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-baseline","state":{"s":"fevirota","left":4,"right":4}}]},"body":["A few inputs look like they might need their own handling: \"rhythm\", which has no vowels at all; \"aA\", whose two vowels differ only in case; and \".,aE!\", where punctuation sits between the vowels.","Take each one in turn and decide whether the skip-and-swap rule already covers it or whether it needs something extra."]},{"id":"no-vowels-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"What happens when the string has no vowels?","workspacePanel":"visualizer","options":[{"id":"cross-unchanged","label":"Both pointers skip every character and cross without a single swap, so the string is returned unchanged","rationale":"No character is a vowel, so neither pointer ever stops to swap; they pass each other and the original string comes back as is.","isCorrect":true},{"id":"swap-ends","label":"The first and last characters get swapped","rationale":"A swap only happens once both pointers are on vowels. With no vowels, the swap step is never reached.","isCorrect":false},{"id":"infinite","label":"The pointers keep skipping forever","rationale":"Each pointer stops stepping once it would pass the other, so the loop ends as soon as they cross.","isCorrect":false}],"answer":"\"rhythm\" comes back unchanged. With no vowels to land on, the pointers cross before any swap, which is exactly the right answer.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"no-vowels-state","state":{"s":"rhythm","left":0,"right":5}}]},"summary":"For s = \"rhythm\", both pointers start at the ends and start stepping inward."},{"id":"mixed-case-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"Do \"a\" and \"A\" swap, or is it a no-op?","workspacePanel":"visualizer","options":[{"id":"both-count","label":"They swap; the case order flips, so the answer is \"Aa\"","rationale":"They are different characters at different indices, so trading them moves the uppercase to the front and the lowercase to the back: \"Aa\".","isCorrect":true},{"id":"same-letter","label":"It is a no-op; \"a\" and \"A\" are the same letter, so swapping changes nothing","rationale":"A no-op only happens when the two characters are identical, like swapping \"e\" with \"e\". \"a\" and \"A\" are distinct characters, so the swap is visible.","isCorrect":false},{"id":"lower-only","label":"Nothing swaps; only lowercase \"a\" is a vowel, so \"A\" is skipped","rationale":"If the membership test left out uppercase, the right pointer would skip past \"A\" and no swap would land. Both cases have to count.","isCorrect":false}],"answer":"\"a\" and \"A\" are distinct characters, so the swap is real and flips the case order to \"Aa\". A swap is only a no-op when both characters are identical.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"mixed-case-state","state":{"s":"aA","left":0,"right":1}}]},"summary":"For s = \"aA\", both pointers land on vowels: left on \"a\" at index 0 and right on \"A\" at index 1."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Two pointers, a membership test, and one inner-guarded swap carry the whole thing.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"s":"favorite","left":0,"right":7}}]},"body":["Hold the vowels in a membership set so the case test is one lookup. Start a pointer at each end. Step each pointer inward while it is on a non-vowel, swap the two vowels you land on, and move both inward. Stop once the pointers meet, then return the rebuilt string."]},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build the two-pointer vowel swap","summary":"Now turn the rule into code: build the vowel set, start a pointer at each end, loop while they are apart, skip non-vowels inward from each side, swap the two vowels you land on and step both in, then join the characters back into a string.","workspacePanel":"code","checkpoints":[{"id":"build-vowel-set","title":"Build vowel membership state","description":"Create a reusable set or equivalent membership test for all lowercase and uppercase vowels.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"set-membership","fact":"initializes_set_state","scope":"convert-to-set","readMode":"set-membership-value-query-v1"}]},"commonMistakes":["Only including lowercase vowels","Checking vowels with repeated string scans instead of reusable membership state"],"hint":"Put all ten vowel characters into a set-like structure.","semanticSpec":{"intent":"Initialize reusable vowel membership state.","doneWhen":"The code creates a set-like membership structure for vowel checks before the pointer loop.","shouldFailWhen":"This step should fail if vowel membership is not represented as reusable state.","roles":["vowel membership state"],"mustProve":["The solution initializes set-like vowel membership state."],"mustNotAccept":["Repeated ad hoc string scans without reusable membership state."],"proofSnippets":[{"id":"py-reverse-vowels-build-vowel-set-chapter","language":"python","code":"class Solution:\n    def reverseVowels(self, s: str) -> str:\n        vowels = set('aeiouAEIOU')"}]}},{"id":"init-pointers","title":"Initialize boundary pointers","description":"Start one pointer at the first character and the other at the last character.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"initializes_boundary_pointers","scope":"init-pointers","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Setting the right pointer to the string length instead of the last index","Starting both pointers at the same side"],"hint":"Use the inclusive first and last valid indices.","semanticSpec":{"intent":"Initialize boundary pointers over the mutable character sequence.","doneWhen":"One pointer starts at the first character and the other starts at the final valid character index.","shouldFailWhen":"This step should fail if either pointer is missing, starts on the wrong side, or uses an invalid upper bound.","roles":["left boundary pointer","right boundary pointer","character sequence"],"mustProve":["The left pointer starts at the first index.","The right pointer starts at the final valid index."],"mustNotAccept":["A right pointer initialized to the sequence length.","Both pointers starting from the same side."],"proofSnippets":[{"id":"py-reverse-vowels-init-pointers-chapter","language":"python","code":"class Solution:\n    def reverseVowels(self, s: str) -> str:\n        chars = list(s)\n        vowels = set('aeiouAEIOU')\n        left = 0\n        right = len(chars) - 1"}]}},{"id":"main-loop","title":"Loop while pointers are apart","description":"Continue until the left and right pointers meet or cross.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"loops_while_pointers_apart","scope":"main-loop","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Using a loop that can keep running after the pointers cross","Scanning with only one pointer"],"hint":"The outer loop should be guarded by left being strictly before right.","semanticSpec":{"intent":"Loop while the vowel-search boundary pointers are still apart.","doneWhen":"The outer loop guard compares the left and right boundary pointers.","shouldFailWhen":"This step should fail if the loop ignores either pointer or keeps running after they meet.","roles":["left boundary pointer","right boundary pointer","outer loop guard"],"mustProve":["The loop condition uses both boundary pointers."],"mustNotAccept":["A one-pointer scan as the main reversal loop.","A loop that can continue after the pointers cross."],"proofSnippets":[{"id":"py-reverse-vowels-main-loop-chapter","language":"python","code":"class Solution:\n    def reverseVowels(self, s: str) -> str:\n        chars = list(s)\n        vowels = set('aeiouAEIOU')\n        left = 0\n        right = len(chars) - 1\n        while left < right:\n            pass"}]}},{"id":"skip-left","title":"Skip non-vowels from the left","description":"Move the left pointer forward until it lands on a vowel or reaches the right pointer.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"skips_left_until_boundary_filter_match","scope":"skip-left","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Moving left without checking vowel membership","Forgetting to keep left before right while skipping"],"hint":"Advance left while the current character is not a vowel.","semanticSpec":{"intent":"Advance the left pointer past non-vowels.","doneWhen":"Inside the outer loop, the left pointer moves right while its current character fails the vowel-membership test.","shouldFailWhen":"This step should fail if left advances without checking vowel membership or ignores the right boundary.","roles":["left boundary pointer","right boundary pointer","vowel membership state"],"mustProve":["The left pointer skip is guarded by vowel membership.","The skip preserves the left-before-right boundary."],"mustNotAccept":["Advancing left unconditionally.","Skipping based on a non-vowel-unrelated predicate."],"proofSnippets":[{"id":"py-reverse-vowels-skip-left-chapter","language":"python","code":"class Solution:\n    def reverseVowels(self, s: str) -> str:\n        chars = list(s)\n        vowels = set('aeiouAEIOU')\n        left = 0\n        right = len(chars) - 1\n        while left < right:\n            while left < right and chars[left] not in vowels:\n                left += 1"}]}},{"id":"skip-right","title":"Skip non-vowels from the right","description":"Move the right pointer backward until it lands on a vowel or reaches the left pointer.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"skips_right_until_boundary_filter_match","scope":"skip-right","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Moving right in the wrong direction","Skipping only lowercase vowels"],"hint":"Retreat right while the current character is not a vowel.","semanticSpec":{"intent":"Retreat the right pointer past non-vowels.","doneWhen":"Inside the outer loop, the right pointer moves left while its current character fails the vowel-membership test.","shouldFailWhen":"This step should fail if right retreats without checking vowel membership or ignores the left boundary.","roles":["left boundary pointer","right boundary pointer","vowel membership state"],"mustProve":["The right pointer skip is guarded by vowel membership.","The skip preserves the left-before-right boundary."],"mustNotAccept":["Retreating right unconditionally.","Skipping only one vowel case."],"proofSnippets":[{"id":"py-reverse-vowels-skip-right-chapter","language":"python","code":"class Solution:\n    def reverseVowels(self, s: str) -> str:\n        chars = list(s)\n        vowels = set('aeiouAEIOU')\n        left = 0\n        right = len(chars) - 1\n        while left < right:\n            while left < right and chars[left] not in vowels:\n                left += 1\n            while left < right and chars[right] not in vowels:\n                right -= 1"}]}},{"id":"swap-and-advance","title":"Swap vowels and move inward","description":"When both pointers are on vowels, swap those characters and then move both pointers inward.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"swaps_boundary_values","scope":"swap-values","readMode":"two-pointer-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"moves_boundary_pointers_inward","scope":"move-pointers","readMode":"two-pointer-value-query-v1"}]}]},"commonMistakes":["Swapping characters before both pointers land on vowels","Forgetting to advance both pointers after a swap"],"hint":"Swap the two boundary entries, then move left forward and right backward.","semanticSpec":{"intent":"Swap the two selected vowels and move both pointers inward.","doneWhen":"After the skip loops, the code swaps the boundary characters and advances both pointers inward.","shouldFailWhen":"This step should fail if the code only swaps, only moves, or swaps before the boundary positions are selected.","roles":["character sequence","left boundary pointer","right boundary pointer"],"mustProve":["The selected boundary values are swapped.","Both boundary pointers move inward after the swap."],"mustNotAccept":["Moving pointers without swapping the selected vowels.","Swapping unrelated positions."],"proofSnippets":[{"id":"py-reverse-vowels-swap-and-advance-chapter","language":"python","code":"class Solution:\n    def reverseVowels(self, s: str) -> str:\n        chars = list(s)\n        vowels = set('aeiouAEIOU')\n        left = 0\n        right = len(chars) - 1\n        while left < right:\n            while left < right and chars[left] not in vowels:\n                left += 1\n            while left < right and chars[right] not in vowels:\n                right -= 1\n            if left < right:\n                chars[left], chars[right] = chars[right], chars[left]\n                left += 1\n                right -= 1"}]}},{"id":"return-string","title":"Return the rebuilt string","description":"Return the mutated character list as a string.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"returns_mutated_boundary_sequence","scope":"return-sequence","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Returning the character list instead of a string","Returning the original string after mutating a copy"],"hint":"Join the mutable characters back into one string.","semanticSpec":{"intent":"Return a string derived from the mutated character sequence.","doneWhen":"After the pointer loop, the code returns the boundary-mutated character sequence rebuilt as a string.","shouldFailWhen":"This step should fail if the return ignores the mutated character sequence.","roles":["mutated character sequence","return string"],"mustProve":["The return occurs after the swap loop.","The returned value is derived from the mutated character sequence."],"mustNotAccept":["Returning the original input string.","Returning an unrelated string."],"proofSnippets":[{"id":"py-reverse-vowels-return-string-chapter","language":"python","code":"class Solution:\n    def reverseVowels(self, s: str) -> str:\n        chars = list(s)\n        vowels = set('aeiouAEIOU')\n        left = 0\n        right = len(chars) - 1\n        while left < right:\n            while left < right and chars[left] not in vowels:\n                left += 1\n            while left < right and chars[right] not in vowels:\n                right -= 1\n            if left < right:\n                chars[left], chars[right] = chars[right], chars[left]\n                left += 1\n                right -= 1\n        return ''.join(chars)"}]}}]},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","summary":"Skip non-vowels from both ends, swap the vowels you land on, and close in until the pointers meet.","workspacePanel":"code","body":["Reversing the vowels is just swapping mirror pairs: the outermost remaining vowel from each end trades places, then you move in. No side list is needed once you see that.","The skip has to repeat while a pointer is on a non-vowel, and a swap only happens while the pointers are still apart. Those two guards are what keep a consonant from ever moving."],"takeaways":[{"title":"Reversal is mirror swaps","body":"The k-th vowel from the front trades with the k-th from the back, so two pointers closing in reverse the vowels with no extra list."},{"title":"Skip with a loop","body":"A pointer must keep stepping while it is on a non-vowel; one step stops short on back-to-back consonants and swaps a fixed character."},{"title":"Both ends decide vowels the same way","body":"A single membership set holding both cases of a, e, i, o, u answers \"is this a vowel\" for either pointer in one lookup."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
