{"id":"reverse-string","title":"Reverse 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":"Reverse an array of characters in place.\n\nFor TraceCode, return the same array after reversing it so the result can be checked.","examples":[{"input":"s = [\"h\", \"e\", \"l\", \"l\", \"o\"]","output":"[\"o\", \"l\", \"l\", \"e\", \"h\"]","explanation":"The first and last characters swap, then the next pair swaps."},{"input":"s = [\"H\", \"a\", \"n\", \"n\", \"a\", \"h\"]","output":"[\"h\", \"a\", \"n\", \"n\", \"a\", \"H\"]","explanation":"The middle pair contains equal characters, so the visible value stays the same."},{"input":"s = [\"a\"]","output":"[\"a\"]","explanation":"A one-character array is already reversed."}],"constraints":[{"id":"1-len-s-10-5","text":"1 <= len(s) <= 10^5","check":{"kind":"sizeRange","target":"s","measure":"arrayLength","min":1,"max":100000}},{"id":"s-i-is-a-printable-ascii-character","text":"s[i] is a printable ASCII character."},{"id":"the-array-should-be-reversed-in-place","text":"The array should be reversed in place."}],"starterCode":"class Solution:\n    def reverseString(self, s: list[str]) -> list[str]:\n        # Your code here\n        pass","functionName":"reverseString","testCases":[{"id":"1","input":{"s":["h","e","l","l","o"]},"expected":["o","l","l","e","h"],"description":"Odd-length word."},{"id":"2","input":{"s":["H","a","n","n","a","h"]},"expected":["h","a","n","n","a","H"],"description":"Even-length word."},{"id":"3","input":{"s":["a"]},"expected":["a"],"description":"Single character."},{"id":"4","input":{"s":["1","2","3","4","5"]},"expected":["5","4","3","2","1"],"description":"Digits are characters too."},{"id":"5","input":{"s":["T","C"]},"expected":["C","T"],"description":"Two-character swap."},{"id":"h1","input":{"s":[" ","a","!"]},"expected":["!","a"," "],"description":"Printable punctuation and space."},{"id":"h2","input":{"s":["r","a","c","e","c","a","r"]},"expected":["r","a","c","e","c","a","r"],"description":"Palindrome input remains visually unchanged."},{"id":"h3","input":{"s":["a","b","c","d"]},"expected":["d","c","b","a"],"description":"Even-length distinct letters."},{"id":"h4","input":{"s":["Z"]},"expected":["Z"],"description":"A single printable character stays unchanged."},{"id":"h5","input":{"s":["m","o","o","n"]},"expected":["n","o","o","m"],"description":"Four characters reverse cleanly in place."}],"hints":[{"level":1,"content":"Only pairs from opposite ends need to move.","revealPattern":false},{"level":2,"content":"Use one pointer at the start and one at the end, then move both inward.","revealPattern":true},{"level":3,"content":"Swap s[left] with s[right], then increment left and decrement right until they meet.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"copy-reversed","name":"Build a reversed copy","summary":"Create a new array with elements from right to left.","decisionReason":"It produces the right order, but allocating a full second array breaks the in-place requirement and costs O(n) extra space.","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":"In-place two-pointer swaps","summary":"Swap the outer pair of characters, then move both pointers inward.","decisionReason":"Each mirror pair is swapped exactly once with O(1) extra space, reversing the array in place as the problem requires.","complexity":{"time":"O(n)","space":"O(1)"},"tradeoffs":["Runs in O(n) time and uses O(1) space."],"isOptimal":true},{"id":"nested-swaps","name":"Repeated shifting","summary":"Move each character to the front by shifting the rest of the array.","decisionReason":"It stays in place but shifts the whole tail on every move, doing O(n^2) work where the swap approach does O(n).","complexity":{"time":"O(n^2)","space":"O(1)"},"tradeoffs":["Runs in O(n^2) time and uses O(1) space."],"isOptimal":false}]},"codingCheckpoints":[{"id":"init-pointers","title":"Initialize boundary pointers","description":"Start one pointer at the first index and the other at the last index.","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 len(s) instead of len(s) - 1","Starting both pointers on the same side"],"hint":"Use the first and last valid indices.","semanticSpec":{"intent":"Initialize the two boundary pointers for in-place reversal.","doneWhen":"One pointer starts at the first index and the other starts at the last valid index.","shouldFailWhen":"This step should fail if either boundary pointer is missing or off by one.","roles":["left boundary pointer","right boundary pointer","input array"],"mustProve":["The left pointer starts at index 0.","The right pointer starts at the final valid index."],"mustNotAccept":["A right pointer initialized to len(s).","Both pointers starting on the same side."],"proofSnippets":[{"id":"py-reverse-string-init-pointers","language":"python","code":"class Solution:\n    def reverseString(self, s: list[str]) -> list[str]:\n        left = 0\n        right = len(s) - 1"}]}},{"id":"main-loop","title":"Loop while pointers are apart","description":"Continue swapping while the left pointer is before the right pointer.","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 run after the pointers cross","Stopping before the last outer pair is swapped"],"hint":"Use a strict left < right condition.","semanticSpec":{"intent":"Loop while the boundary pointers still select a pair to swap.","doneWhen":"The loop guard compares the left and right boundary pointers.","shouldFailWhen":"This step should fail if the loop ignores either pointer or runs after they meet.","roles":["left boundary pointer","right boundary pointer","loop guard"],"mustProve":["The loop condition uses both boundary pointers."],"mustNotAccept":["A fixed-count loop unrelated to the pointers.","A loop that continues after the pointers cross."],"proofSnippets":[{"id":"py-reverse-string-main-loop","language":"python","code":"class Solution:\n    def reverseString(self, s: list[str]) -> list[str]:\n        left = 0\n        right = len(s) - 1\n        while left < right:\n            pass"}]}},{"id":"swap-values","title":"Swap boundary values","description":"Swap the characters currently selected by the two pointers.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"swaps_boundary_values","scope":"swap-values","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Overwriting one side before saving its value","Swapping values from the wrong indices"],"hint":"Exchange s[left] and s[right].","semanticSpec":{"intent":"Swap the values at the current boundary pointers.","doneWhen":"The code exchanges the array values selected by the left and right pointers.","shouldFailWhen":"This step should fail if the code writes only one side or swaps unrelated indices.","roles":["input array","left boundary pointer","right boundary pointer"],"mustProve":["The write uses both boundary indices.","The values are exchanged between those two positions."],"mustNotAccept":["Overwriting both sides with the same value.","Swapping unrelated array positions."],"proofSnippets":[{"id":"py-reverse-string-swap-values","language":"python","code":"class Solution:\n    def reverseString(self, s: list[str]) -> list[str]:\n        left = 0\n        right = len(s) - 1\n        while left < right:\n            s[left], s[right] = s[right], s[left]"}]}},{"id":"move-pointers","title":"Move both pointers inward","description":"After each swap, advance the left pointer and retreat the right pointer.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"moves_boundary_pointers_inward","scope":"move-pointers","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Moving only one pointer","Moving a pointer in the wrong direction"],"hint":"Increment left and decrement right.","semanticSpec":{"intent":"Move both boundary pointers inward after a swap.","doneWhen":"The left pointer advances and the right pointer retreats inside the loop.","shouldFailWhen":"This step should fail if only one pointer moves or either pointer moves outward.","roles":["left boundary pointer","right boundary pointer"],"mustProve":["The left pointer moves toward the center.","The right pointer moves toward the center."],"mustNotAccept":["Moving only one boundary pointer.","Moving a boundary pointer in the wrong direction."],"proofSnippets":[{"id":"py-reverse-string-move-pointers","language":"python","code":"class Solution:\n    def reverseString(self, s: list[str]) -> list[str]:\n        left = 0\n        right = len(s) - 1\n        while left < right:\n            s[left], s[right] = s[right], s[left]\n            left += 1\n            right -= 1"}]}},{"id":"return-array","title":"Return the reversed array","description":"Return the same array after the in-place reversal.","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 a new unrelated array","Returning before the swap loop finishes"],"hint":"Return s after all boundary swaps are complete.","semanticSpec":{"intent":"Return the same array after the in-place boundary swaps finish.","doneWhen":"The terminal return references the mutated input array after the loop.","shouldFailWhen":"This step should fail if the return ignores the mutated sequence or happens before the loop completes.","roles":["input array","mutated boundary sequence","return value"],"mustProve":["The return occurs after the swap loop.","The returned value is the boundary-mutated sequence."],"mustNotAccept":["Returning a newly unrelated array.","Returning before all boundary swaps finish."],"proofSnippets":[{"id":"py-reverse-string-return-array","language":"python","code":"class Solution:\n    def reverseString(self, s: list[str]) -> list[str]:\n        left = 0\n        right = len(s) - 1\n        while left < right:\n            s[left], s[right] = s[right], s[left]\n            left += 1\n            right -= 1\n        return s"}]}}],"slides":[{"id":"read-the-problem","chapter":"The problem","kind":"info","eyebrow":"Read the problem","title":"Flip the array end to end, in place","workspacePanel":"problem","body":["You get an array of single characters and must reverse its order. The first character has to end up last, the last has to end up first, and you change the array you were handed rather than returning a fresh one.","The first instinct is to build a brand-new array filling it from the back. Watch that idea, then watch what it costs."]},{"id":"brute-force","chapter":"The problem","kind":"code-trace","eyebrow":"The obvious way","title":"Build a fresh array from back to front","summary":"Filling a new array from the back gives the right order, but it keeps a second array alive for every character. Watch how that copy grows as the input gets longer.","workspacePanel":"trace","body":["Walk the input from the last index down to the first, appending each character to a new array, then hand that new array back."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"result = []\ni = len(s) - 1\nwhile i >= 0:\n    result.append(s[i])\n    i -= 1\nreturn result","steps":[{"id":"take-last","title":"Copy the last character into a new array","codeLine":4,"summary":"Start at index 4 on \"o\" and append it to result, which begins empty. result is now [\"o\"], a separate array being built alongside s.","state":{"s":"hello","i":4,"arrays":[{"name":"result","values":["o"]}]}},{"id":"keep-copying","title":"Keep walking left, copying each character","codeLine":4,"summary":"Step down through indices 3, 2, 1, appending \"l\", \"l\", \"e\". result holds [\"o\", \"l\", \"l\", \"e\"] while s is untouched.","state":{"s":"hello","i":1,"arrays":[{"name":"result","values":["o","l","l","e"]}]}},{"id":"finish-copy","title":"Copy the first character and return","codeLine":6,"summary":"Index 0 appends \"h\". result is [\"o\", \"l\", \"l\", \"e\", \"h\"] and gets returned, holding one entry for every character in s.","state":{"s":"hello","i":0,"arrays":[{"name":"result","values":["o","l","l","e","h"]}]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const result = [];\nlet i = s.length - 1;\nwhile (i >= 0) {\n    result.push(s[i]);\n    i--;\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7},"statementBundles":{"5":{"startLine":5,"endLine":6}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const result: Array<string> = [];\nlet i = s.length - 1;\nwhile (i >= 0) {\n    result.push(s[i]);\n    i--;\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7},"statementBundles":{"5":{"startLine":5,"endLine":6}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<String> result = new ArrayList<>();\nint i = s.size() - 1;\nwhile (i >= 0) {\n    result.add(s.get(i));\n    i--;\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7},"statementBundles":{"5":{"startLine":5,"endLine":6}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<string> result = new();\nint i = s.Count - 1;\nwhile (i >= 0) {\n    result.Add(s[i]);\n    i--;\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7},"statementBundles":{"5":{"startLine":5,"endLine":6}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<string> result;\nint i = s.size() - 1;\nwhile (i >= 0) {\n    result.push_back(s[i]);\n    i--;\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7},"statementBundles":{"5":{"startLine":5,"endLine":6}}}}}},{"id":"brute-cost","chapter":"The problem","kind":"case-probe","eyebrow":"Count the cost","title":"What grows as the input array gets longer?","workspacePanel":"trace","summary":"The copied version returns the right order while keeping result sitting beside the original array s.","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"result = []\ni = len(s) - 1\nwhile i >= 0:\n    result.append(s[i])\n    i -= 1\nreturn result","steps":[{"id":"full-copy-cost","title":"result now holds a full second copy beside s","codeLine":6,"summary":"The walk is done: result carries one entry for every character in s, so a five-character input leaves a five-entry second array alive alongside the original. On a longer input that second array grows right along with it.","state":{"s":"hello","arrays":[{"name":"result","values":["o","l","l","e","h"]}]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const result = [];\nlet i = s.length - 1;\nwhile (i >= 0) {\n    result.push(s[i]);\n    i--;\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7},"statementBundles":{"5":{"startLine":5,"endLine":6}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const result: Array<string> = [];\nlet i = s.length - 1;\nwhile (i >= 0) {\n    result.push(s[i]);\n    i--;\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7},"statementBundles":{"5":{"startLine":5,"endLine":6}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<String> result = new ArrayList<>();\nint i = s.size() - 1;\nwhile (i >= 0) {\n    result.add(s.get(i));\n    i--;\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7},"statementBundles":{"5":{"startLine":5,"endLine":6}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<string> result = new();\nint i = s.Count - 1;\nwhile (i >= 0) {\n    result.Add(s[i]);\n    i--;\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7},"statementBundles":{"5":{"startLine":5,"endLine":6}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<string> result;\nint i = s.size() - 1;\nwhile (i >= 0) {\n    result.push_back(s[i]);\n    i--;\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7},"statementBundles":{"5":{"startLine":5,"endLine":6}}}}},"options":[{"id":"extra-array","label":"A second array as long as the input, since every character is copied into result","rationale":"result ends up holding one entry per character, so on a long array it doubles the memory in use even though the problem says to reverse the one array you were given.","isCorrect":true},{"id":"nothing-extra","label":"Nothing extra, because it reuses the characters already stored in s","rationale":"result is a brand-new array filled before anything is returned. Each character is copied into it, so a longer input means a longer second array.","isCorrect":false},{"id":"more-passes","label":"The number of passes over the array, since longer inputs need more walks","rationale":"It is always one walk from the last index to the first. What scales with the input is the size of result, not how many times the array is traversed.","isCorrect":false}],"answer":"result grows to match the input length, so a long array carries a full second copy. The problem asks for an in-place reversal, and that extra array is exactly the cost an in-place method avoids."},{"id":"copy-recap","chapter":"The idea","kind":"info","eyebrow":"Reuse the array","title":"The copy works, but it pays for a second array","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"recap-state","state":{"s":"hello"}}]},"body":["Filling a fresh array from back to front gives the right order, but it keeps a full second array alive the whole time, and the problem asks us to reverse the one array we were handed.","So the goal narrows: rearrange the characters inside this same array. Look at where each character has to land in the reversed order and the move you need becomes clear."]},{"id":"mirror-probe","chapter":"The idea","kind":"case-probe","eyebrow":"Find the move","title":"In the reversed array, where does the character at index 0 end up?","workspacePanel":"visualizer","summary":"Compare the input [\"h\", \"e\", \"l\", \"l\", \"o\"] with its reverse [\"o\", \"l\", \"l\", \"e\", \"h\"], index by index.","options":[{"id":"trades-mirror","label":"At the last index, having traded places with the character that started there","rationale":"\"h\" at index 0 and \"o\" at index 4 swap ends; index 1 and index 3 swap; the middle character at index 2 already sits in its mirror slot. Every character just trades with the one the same distance in from the other end.","isCorrect":true},{"id":"shifts-one","label":"One slot to the right of where it started","rationale":"A reversal is not a shift. The first character jumps all the way to the last slot, not one step over.","isCorrect":false},{"id":"stays-put","label":"It stays at index 0, because reversing only rearranges the middle","rationale":"The first character moves all the way to the back. The ends change before the middle does.","isCorrect":false}],"answer":"Index 0 trades with the last index, index 1 with the second-to-last, and the middle character is already where it belongs. Reversing the array is nothing more than swapping these mirror pairs, which means it can happen inside the one array.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"mirror-state","state":{"s":"hello","left":0,"right":4}}]}},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Swap mirror pairs in place, or fill a fresh reversed array?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"s":"hello","left":0,"right":4}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"Two pointers at the ends, closing in","workspacePanel":"visualizer","body":["Here is the array we are about to reverse in place, untouched. The plan is simple: one pointer will start at index 0 and the other at the last index, and each round swaps the two characters they rest on, then steps the left pointer forward and the right pointer back.","When the pointers meet or cross, every mirror pair has been swapped and the array is reversed. Start with the pointers on the two ends and walk the first swap."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"s":"hello"}}]}},{"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":"first-swap","state":{"s":"hello","left":0,"right":4}},{"id":"second-swap","state":{"s":"oellh","left":1,"right":3}},{"id":"stop","state":{"s":"olleh","left":2,"right":2}}]},"beats":[{"id":"first-swap","figure":"setup","title":"Left is on \"h\", right is on \"o\". What changes?","summary":"Left holds index 0 and right holds index 4.","prompt":"The pointers rest on the outermost pair, \"h\" and \"o\".","options":[{"id":"swap-move","label":"Swap \"h\" and \"o\" to get [\"o\", \"e\", \"l\", \"l\", \"h\"], then step both pointers inward","rationale":"The outer pair trades ends, then left advances to 1 and right retreats to 3 to take on the next pair.","isCorrect":true},{"id":"move-only","label":"Move both pointers inward without swapping","rationale":"The pointers are on the pair that needs to trade. Skipping the swap leaves \"h\" and \"o\" at the wrong ends.","isCorrect":false},{"id":"swap-stay","label":"Swap \"h\" and \"o\" but leave the pointers in place","rationale":"Without stepping inward the same pair gets swapped again next round, putting \"h\" and \"o\" right back where they started.","isCorrect":false}],"answer":"Swapping gives [\"o\", \"e\", \"l\", \"l\", \"h\"]. Then left moves to index 1 and right to index 3."},{"id":"second-swap","figure":"setup","title":"Left is on \"e\", right is on \"l\". What is the array after this swap?","summary":"From [\"o\", \"e\", \"l\", \"l\", \"h\"], left holds index 1 and right holds index 3.","prompt":"The next pair to trade is \"e\" at index 1 and \"l\" at index 3.","options":[{"id":"olleh","label":"[\"o\", \"l\", \"l\", \"e\", \"h\"]","rationale":"\"e\" and \"l\" trade places, so index 1 becomes \"l\" and index 3 becomes \"e\"; the rest is already settled.","isCorrect":true},{"id":"oellh","label":"[\"o\", \"e\", \"l\", \"l\", \"h\"]","rationale":"That is the array before this swap. The \"e\" and \"l\" at index 1 and index 3 still have to trade.","isCorrect":false},{"id":"hlleo","label":"[\"h\", \"l\", \"l\", \"e\", \"o\"]","rationale":"That undoes the first swap at the ends. \"o\" and \"h\" already traded and stay put; only index 1 and index 3 change now.","isCorrect":false}],"answer":"Swapping \"e\" and \"l\" gives [\"o\", \"l\", \"l\", \"e\", \"h\"]. Left then moves to index 2 and right to index 2."},{"id":"stop","figure":"setup","title":"When both pointers reach index 2, does another swap happen?","summary":"left and right are both on the middle character \"l\".","prompt":"left equals right, both at index 2.","options":[{"id":"stop-here","label":"No. The pointers have met, so the loop stops and the array is returned","rationale":"The loop continues only while left is strictly before right. Once they land on the same index there is no pair left, and the single middle character is already in place.","isCorrect":true},{"id":"swap-self","label":"Yes. The character at index 2 swaps with itself","rationale":"Swapping a character with itself changes nothing, and letting the loop reach this point is wasted work. Stopping when the pointers meet avoids it cleanly.","isCorrect":false},{"id":"keep-going","label":"Yes. The pointers keep crossing and swap again","rationale":"If the loop ran past the meeting point it would re-swap pairs already in place and undo the reversal. It has to stop the moment left is no longer before right.","isCorrect":false}],"answer":"left is no longer before right, so the loop ends. [\"o\", \"l\", \"l\", \"e\", \"h\"] is the reversed array."}]},{"id":"crossing-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Can the loop just run while the left pointer is still inside the array?","summary":"Bounding the loop on the left pointer alone looks natural: keep swapping while left is a valid index, stepping both pointers each round. It lines up with the right answer for the first half of the array. Watch what the second half does to it.","workspacePanel":"trace","pitfall":"The loop below continues while left stays inside the array instead of stopping once left reaches right.","whyItMatters":"The loop has to stop the moment the pointers meet. Run it any further and it keeps swapping pairs it already fixed, trading every mirror pair a second time and landing back on the original array.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"left = 0\nright = len(s) - 1\nwhile left < len(s):\n    s[left], s[right] = s[right], s[left]\n    left += 1\n    right -= 1\nreturn s","steps":[{"id":"first-half","title":"The first swaps look correct","codeLine":4,"summary":"On s = [\"a\", \"b\", \"c\", \"d\"], left at 0 and right at 3 swap to give [\"d\", \"b\", \"c\", \"a\"]. So far this matches the real reversal.","state":{"s":"dbca","left":0,"right":3}},{"id":"second-swap","title":"The second swap finishes the reversal","codeLine":4,"summary":"left is 1 and right is 2; swapping gives [\"d\", \"c\", \"b\", \"a\"], the fully reversed array. But left is only 2 now, still less than the length 4, so the loop keeps going.","state":{"s":"dcba","left":1,"right":2}},{"id":"reswap","title":"It crosses and swaps an already-fixed pair","codeLine":4,"summary":"left is 2 and right is 1, past each other. Swapping them trades \"b\" and \"c\" back, turning [\"d\", \"c\", \"b\", \"a\"] into [\"d\", \"b\", \"c\", \"a\"].","state":{"s":"dbca","left":2,"right":1}},{"id":"broken","title":"One more swap undoes the reversal","codeLine":4,"summary":"left is 3 and right is 0, so this swap line trades \"d\" and \"a\" back, turning [\"d\", \"c\", \"b\", \"a\"] into [\"a\", \"b\", \"c\", \"d\"]. The same swap that did the work earlier now runs once too often and reverses it back.","state":{"s":"abcd","left":3,"right":0}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let left = 0;\nlet right = s.length - 1;\nwhile (left < s.length) {\n    const entry = [s[right], s[left]];\n    s[left] = entry[0];\n    s[right] = entry[1];\n    left++;\n    right--;\n}\nreturn s;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":7,"6":8,"7":10},"statementBundles":{"4":{"startLine":4,"endLine":6},"6":{"startLine":8,"endLine":9}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let left = 0;\nlet right = s.length - 1;\nwhile (left < s.length) {\n    const entry = [s[right], s[left]];\n    s[left] = entry[0];\n    s[right] = entry[1];\n    left++;\n    right--;\n}\nreturn s;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":7,"6":8,"7":10},"statementBundles":{"4":{"startLine":4,"endLine":6},"6":{"startLine":8,"endLine":9}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int left = 0;\nint right = s.size() - 1;\nwhile (left < s.size()) {\n    List<String> entry = new ArrayList<>(List.of(s.get(right), s.get(left)));\n    s.set(left, entry.get(0));\n    s.set(right, entry.get(1));\n    left++;\n    right--;\n}\nreturn s;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":7,"6":8,"7":10},"statementBundles":{"4":{"startLine":4,"endLine":6},"6":{"startLine":8,"endLine":9}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int left = 0;\nint right = s.Count - 1;\nwhile (left < s.Count) {\n    List<string> entry = new() { s[right], s[left] };\n    s[left] = entry[0];\n    s[right] = entry[1];\n    left++;\n    right--;\n}\nreturn s;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":7,"6":8,"7":10},"statementBundles":{"4":{"startLine":4,"endLine":6},"6":{"startLine":8,"endLine":9}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"size_t left = 0;\nint right = s.size() - 1;\nwhile (left < s.size()) {\n    pair<string, string> entry{s[right], s[static_cast<int>(left)]};\n    s[static_cast<int>(left)] = entry.first;\n    s[right] = entry.second;\n    left++;\n    right--;\n}\nreturn s;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":7,"6":8,"7":10},"statementBundles":{"4":{"startLine":4,"endLine":6},"6":{"startLine":8,"endLine":9}}}}}},{"id":"edge-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","summary":"The reversal is sound now: swap the outer pair, step inward, and stop the instant the pointers meet.","ctaLabel":"Check edge cases","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-baseline","state":{"s":"olleh","left":2,"right":2}}]},"body":["[\"a\"] has one character with nothing to pair it with. [\"h\", \"e\", \"l\", \"l\", \"o\"] has a middle character whose mirror is itself.","Take each one and decide whether the swap-and-stop rule already covers it or whether it needs something extra."]},{"id":"single-char-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"What does the loop do when the array holds one character?","workspacePanel":"visualizer","options":[{"id":"no-swap","label":"Nothing. left already equals right, so the loop body never runs and [\"a\"] is returned as is","rationale":"The loop runs only while left is strictly before right. With both at index 0 that test fails immediately, so there is no swap and the single character is left in place.","isCorrect":true},{"id":"self-swap","label":"It swaps the character with itself once","rationale":"A strict left-before-right test is false when both are 0, so the body never executes. No self-swap happens.","isCorrect":false},{"id":"out-of-bounds","label":"It reads past the end of the array and errors","rationale":"right is the last valid index, which is 0 here. The loop simply does not run, so nothing is read out of bounds.","isCorrect":false}],"answer":"[\"a\"] comes back unchanged. With left and right already equal, the strict test stops the loop before any swap, which is exactly right for a one-character array.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-state","state":{"s":"a","left":0,"right":0}}]},"summary":"For s = [\"a\"], left starts at index 0 and right starts at index 0."},{"id":"odd-length-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"With an odd length, what happens to the middle character?","workspacePanel":"visualizer","options":[{"id":"left-alone","label":"It is left alone; the loop stops when the pointers meet on it","rationale":"The middle character of an odd-length array is its own mirror, so it already sits in the right slot. The pointers meet there, the strict test fails, and it is never touched.","isCorrect":true},{"id":"swapped-self","label":"It swaps with itself, which is wasted but harmless","rationale":"A strict left-before-right test means the pointers stop the moment they meet, so the middle is not even reached for a swap, not even a self-swap.","isCorrect":false},{"id":"skipped-wrong","label":"It gets skipped and ends up in the wrong place","rationale":"The middle of an odd-length array is already where it belongs in the reversal, so leaving it untouched is correct.","isCorrect":false}],"answer":"The middle character is its own mirror, so the loop meeting on it and stopping leaves it exactly where the reversed array needs it. Odd lengths need no special case.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"odd-state","state":{"s":"olleh","left":2,"right":2}}]},"summary":"For s = [\"h\", \"e\", \"l\", \"l\", \"o\"], after the outer pairs swap, both pointers land on index 2."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Two pointers, one swap, and a strict stop carry the whole reversal.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"s":"hello","left":0,"right":4}}]},"body":["Start a pointer at each end. While the left pointer is still before the right, swap the two characters they rest on, then move the left pointer forward and the right pointer back. Stop as soon as the pointers meet, and return the same array you were given."]},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build the two-pointer reversal","summary":"Time to build it: start a pointer at each end, loop while the left one is still before the right, swap the pair they rest on, step both inward, and return the same array once they meet.","workspacePanel":"code","checkpoints":[{"id":"init-pointers","title":"Initialize boundary pointers","description":"Start one pointer at the first index and the other at the last index.","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 len(s) instead of len(s) - 1","Starting both pointers on the same side"],"hint":"Use the first and last valid indices.","semanticSpec":{"intent":"Initialize the two boundary pointers for in-place reversal.","doneWhen":"One pointer starts at the first index and the other starts at the last valid index.","shouldFailWhen":"This step should fail if either boundary pointer is missing or off by one.","roles":["left boundary pointer","right boundary pointer","input array"],"mustProve":["The left pointer starts at index 0.","The right pointer starts at the final valid index."],"mustNotAccept":["A right pointer initialized to len(s).","Both pointers starting on the same side."],"proofSnippets":[{"id":"py-reverse-string-init-pointers-chapter","language":"python","code":"class Solution:\n    def reverseString(self, s: list[str]) -> list[str]:\n        left = 0\n        right = len(s) - 1"}]}},{"id":"main-loop","title":"Loop while pointers are apart","description":"Continue swapping while the left pointer is before the right pointer.","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 run after the pointers cross","Stopping before the last outer pair is swapped"],"hint":"Use a strict left < right condition.","semanticSpec":{"intent":"Loop while the boundary pointers still select a pair to swap.","doneWhen":"The loop guard compares the left and right boundary pointers.","shouldFailWhen":"This step should fail if the loop ignores either pointer or runs after they meet.","roles":["left boundary pointer","right boundary pointer","loop guard"],"mustProve":["The loop condition uses both boundary pointers."],"mustNotAccept":["A fixed-count loop unrelated to the pointers.","A loop that continues after the pointers cross."],"proofSnippets":[{"id":"py-reverse-string-main-loop-chapter","language":"python","code":"class Solution:\n    def reverseString(self, s: list[str]) -> list[str]:\n        left = 0\n        right = len(s) - 1\n        while left < right:\n            pass"}]}},{"id":"swap-values","title":"Swap boundary values","description":"Swap the characters currently selected by the two pointers.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"swaps_boundary_values","scope":"swap-values","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Overwriting one side before saving its value","Swapping values from the wrong indices"],"hint":"Exchange s[left] and s[right].","semanticSpec":{"intent":"Swap the values at the current boundary pointers.","doneWhen":"The code exchanges the array values selected by the left and right pointers.","shouldFailWhen":"This step should fail if the code writes only one side or swaps unrelated indices.","roles":["input array","left boundary pointer","right boundary pointer"],"mustProve":["The write uses both boundary indices.","The values are exchanged between those two positions."],"mustNotAccept":["Overwriting both sides with the same value.","Swapping unrelated array positions."],"proofSnippets":[{"id":"py-reverse-string-swap-values-chapter","language":"python","code":"class Solution:\n    def reverseString(self, s: list[str]) -> list[str]:\n        left = 0\n        right = len(s) - 1\n        while left < right:\n            s[left], s[right] = s[right], s[left]"}]}},{"id":"move-pointers","title":"Move both pointers inward","description":"After each swap, advance the left pointer and retreat the right pointer.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"two-pointer","fact":"moves_boundary_pointers_inward","scope":"move-pointers","readMode":"two-pointer-value-query-v1"}]},"commonMistakes":["Moving only one pointer","Moving a pointer in the wrong direction"],"hint":"Increment left and decrement right.","semanticSpec":{"intent":"Move both boundary pointers inward after a swap.","doneWhen":"The left pointer advances and the right pointer retreats inside the loop.","shouldFailWhen":"This step should fail if only one pointer moves or either pointer moves outward.","roles":["left boundary pointer","right boundary pointer"],"mustProve":["The left pointer moves toward the center.","The right pointer moves toward the center."],"mustNotAccept":["Moving only one boundary pointer.","Moving a boundary pointer in the wrong direction."],"proofSnippets":[{"id":"py-reverse-string-move-pointers-chapter","language":"python","code":"class Solution:\n    def reverseString(self, s: list[str]) -> list[str]:\n        left = 0\n        right = len(s) - 1\n        while left < right:\n            s[left], s[right] = s[right], s[left]\n            left += 1\n            right -= 1"}]}},{"id":"return-array","title":"Return the reversed array","description":"Return the same array after the in-place reversal.","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 a new unrelated array","Returning before the swap loop finishes"],"hint":"Return s after all boundary swaps are complete.","semanticSpec":{"intent":"Return the same array after the in-place boundary swaps finish.","doneWhen":"The terminal return references the mutated input array after the loop.","shouldFailWhen":"This step should fail if the return ignores the mutated sequence or happens before the loop completes.","roles":["input array","mutated boundary sequence","return value"],"mustProve":["The return occurs after the swap loop.","The returned value is the boundary-mutated sequence."],"mustNotAccept":["Returning a newly unrelated array.","Returning before all boundary swaps finish."],"proofSnippets":[{"id":"py-reverse-string-return-array-chapter","language":"python","code":"class Solution:\n    def reverseString(self, s: list[str]) -> list[str]:\n        left = 0\n        right = len(s) - 1\n        while left < right:\n            s[left], s[right] = s[right], s[left]\n            left += 1\n            right -= 1\n        return s"}]}}]},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","summary":"Swap the outer pair, step both pointers inward, and stop the moment they meet.","workspacePanel":"code","body":["Reversing an array is just swapping mirror pairs: the k-th character from the front trades with the k-th from the back. Seeing that is what lets the whole thing happen inside the one array, with no second copy.","The strict left-before-right test is what keeps it correct. It stops the loop the instant the pointers meet, so no pair is ever traded twice and the lone middle character of an odd-length array is left where it belongs."],"takeaways":[{"title":"Reversal is mirror swaps","body":"The k-th character from each end trades places, so two pointers closing in reverse the array with no extra copy and O(1) extra space."},{"title":"Stop strictly before the pointers cross","body":"A strict left-before-right loop swaps each pair exactly once; letting it run to or past the meeting point re-swaps fixed pairs and undoes the work."},{"title":"Odd lengths need no special case","body":"The middle character of an odd-length array is its own mirror, so the pointers meeting on it and stopping leaves it correctly in place."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
