{"id":"remove-all-adjacent-duplicates-in-string","title":"Remove All Adjacent Duplicates in String","difficulty":"easy","patterns":["monotonic-stack"],"primaryConcept":"stack-lifo-validation","concepts":["stack-lifo-validation"],"problemForm":"intro","companies":["Amazon","Bloomberg"],"category":"stacks-queues","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"string","primaryParam":"s","sizeMetric":"length","sizes":[8,16,32]},"description":"Given a string `s`, repeatedly remove adjacent pairs of equal characters until no such pair remains. Return the final string.","examples":[{"input":"s = \"abbaca\"","output":"\"ca\"","explanation":"Remove \"bb\" to get \"aaca\", then remove \"aa\" to get \"ca\"."},{"input":"s = \"azxxzy\"","output":"\"ay\"","explanation":"Remove \"xx\" to get \"azzy\", then remove \"zz\" to get \"ay\"."}],"constraints":[{"id":"1-len-s-10-5","text":"1 <= len(s) <= 10^5","check":{"kind":"sizeRange","target":"s","measure":"stringLength","min":1,"max":100000}},{"id":"s-consists-of-lowercase-english-letters","text":"s consists of lowercase English letters.","check":{"kind":"domain","target":"s","selector":"stringChars","allowed":["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]}}],"starterCode":"class Solution:\n    def removeDuplicates(self, s: str) -> str:\n        # Your code here\n        pass","functionName":"removeDuplicates","testCases":[{"id":"1","input":{"s":"abbaca"},"expected":"ca","description":"Canonical cascading removal."},{"id":"2","input":{"s":"azxxzy"},"expected":"ay","description":"Two separate duplicate pairs collapse."},{"id":"3","input":{"s":"a"},"expected":"a","description":"Single character remains unchanged."},{"id":"4","input":{"s":"aaaa"},"expected":"","description":"Repeated duplicates remove everything."},{"id":"h1","input":{"s":"abba"},"expected":"","description":"Removal creates a new adjacent duplicate pair."},{"id":"h2","input":{"s":"abcddcba"},"expected":"","description":"Nested duplicate collapse clears the string."},{"id":"h3","input":{"s":"mnomno"},"expected":"mnomno","description":"No adjacent duplicates are removed."},{"id":"h4","input":{"s":"aaaaaaaaab"},"expected":"ab","description":"Odd duplicate run leaves one survivor."},{"id":"h5","input":{"s":"aabccbdd"},"expected":"","description":"Multiple collapses across the whole string."},{"id":"h6","input":{"s":"baab"},"expected":"","description":"A removal in the middle triggers a second collapse."}],"hints":[{"level":1,"content":"A character can only cancel with the most recent character that survived.","revealPattern":false},{"level":2,"content":"Use a stack of surviving characters. The top is the only character that can pair with the current one.","revealPattern":true},{"level":3,"content":"If the top equals the current character, pop it. Otherwise, push the current character. Join the stack at the end.","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":"rescan-string","name":"Repeatedly rescan and delete pairs","summary":"Delete the first adjacent pair you find, then restart scanning from the beginning.","decisionReason":"Each deletion restarts the scan from the front, so a long run of cancellations rescans the whole string repeatedly, giving O(n^2) work where one pass would do.","complexity":{"time":"O(n^2)","space":"O(n)"},"tradeoffs":["Runs in O(n^2) time and uses O(n) space."],"isOptimal":false},{"id":"survivor-stack","name":"One-pass survivor stack","summary":"Scan once while the stack stores the current reduced string.","decisionReason":"The stack is the reduced prefix after processing each character of s. A matching top cancels the new character immediately; otherwise the character remains as a possible neighbor for later input.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Runs in O(n) time and uses O(n) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-stack","title":"Start a survivor stack","description":"Create an empty stack to hold the characters that have not been removed.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"initializes_empty_stack","scope":"init-stack","readMode":"stack-value-query-v1"}]},"commonMistakes":["Trying to mutate the input string in place","Keeping only the previous raw input character instead of all survivors"],"hint":"The stack should begin empty before scanning `s`.","semanticSpec":{"intent":"Initialize LIFO state for surviving characters.","doneWhen":"An empty stack-like collection exists before the input scan.","shouldFailWhen":"This step should fail if no LIFO state is initialized.","roles":["survivor stack"],"mustProve":["The solution initializes an empty stack."],"mustNotAccept":["Only a scalar previous-character variable."],"proofSnippets":[{"id":"py-remove-adjacent-init-stack","language":"python","code":"class Solution:\n    def removeDuplicates(self, s: str) -> str:\n        stack = []"}]}},{"id":"scan-string","title":"Scan the input string","description":"Visit each character in order so removals follow the original adjacency order.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"scans_input_sequence","scope":"main-loop","readMode":"stack-value-query-v1"}]},"commonMistakes":["Skipping characters after a pop","Sorting the characters before processing"],"hint":"Process `s` from left to right.","semanticSpec":{"intent":"Scan the source string once in input order.","doneWhen":"The solution loops over the input string.","shouldFailWhen":"This step should fail if the input sequence is not scanned.","roles":["input string","current character"],"mustProve":["The solution scans the input sequence."],"mustNotAccept":["Only handling a fixed number of characters."],"proofSnippets":[{"id":"py-remove-adjacent-scan-string","language":"python","code":"class Solution:\n    def removeDuplicates(self, s: str) -> str:\n        stack = []\n        for ch in s:\n            pass"}]}},{"id":"duplicate-check","title":"Compare against the stack top","description":"When the stack is non-empty, compare the current character with the most recent survivor.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"branches_on_reduction_token","scope":"operator-branch","readMode":"stack-value-query-v1"}]},"commonMistakes":["Comparing against the previous input index after it may have been removed","Popping without checking that the stack is non-empty"],"hint":"The duplicate test should read the top of the survivor stack.","semanticSpec":{"intent":"Branch on whether the current character cancels with the stack top.","doneWhen":"The scan condition reads both current character state and stack state.","shouldFailWhen":"This step should fail if the stack top is not part of the branch.","roles":["current character","survivor stack top"],"mustProve":["The solution branches on stack reduction state."],"mustNotAccept":["A branch that ignores the stack top."],"proofSnippets":[{"id":"py-remove-adjacent-duplicate-check","language":"python","code":"class Solution:\n    def removeDuplicates(self, s: str) -> str:\n        stack = []\n        for ch in s:\n            if stack and stack[-1] == ch:\n                pass"}]}},{"id":"pop-duplicate","title":"Remove matching survivors","description":"If the current character matches the stack top, pop that survivor instead of keeping either copy.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"pops_resolved_stack_entry","scope":"pop-entry","readMode":"stack-value-query-v1"}]},"commonMistakes":["Pushing the duplicate character after popping","Removing the wrong end of the survivor collection"],"hint":"A matching pair disappears, so pop the stack top and do not push the current character.","semanticSpec":{"intent":"Pop the stack entry resolved by the current duplicate.","doneWhen":"The duplicate branch removes the LIFO entry.","shouldFailWhen":"This step should fail if duplicates are detected but no stack entry is popped.","roles":["survivor stack"],"mustProve":["The solution pops a resolved stack entry."],"mustNotAccept":["Leaving the duplicate survivor on the stack."],"proofSnippets":[{"id":"py-remove-adjacent-pop-duplicate","language":"python","code":"class Solution:\n    def removeDuplicates(self, s: str) -> str:\n        stack = []\n        for ch in s:\n            if stack and stack[-1] == ch:\n                stack.pop()"}]}},{"id":"push-survivor","title":"Push non-duplicates","description":"If the current character does not cancel, push it as the newest survivor.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"pushes_current_token_value","scope":"push-value","readMode":"stack-value-query-v1"}]},"commonMistakes":["Appending every character before checking for cancellation","Pushing an index when the output needs characters"],"hint":"The non-duplicate path appends the current character to the stack.","semanticSpec":{"intent":"Push current characters that survive cancellation.","doneWhen":"The current scan value is appended to the LIFO state.","shouldFailWhen":"This step should fail if the scan value is never pushed.","roles":["current character","survivor stack"],"mustProve":["The solution pushes the current token value."],"mustNotAccept":["Only pushing constants or unrelated values."],"proofSnippets":[{"id":"py-remove-adjacent-push-survivor","language":"python","code":"class Solution:\n    def removeDuplicates(self, s: str) -> str:\n        stack = []\n        for ch in s:\n            if stack and stack[-1] == ch:\n                stack.pop()\n            else:\n                stack.append(ch)"}]}},{"id":"return-result","title":"Return the reduced string","description":"After the scan, convert the survivor stack back into the final string.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"returns_reduced_stack_outcome","scope":"return-answer","readMode":"stack-value-query-v1"}]},"commonMistakes":["Returning the original input string","Returning the stack object instead of a string"],"hint":"The stack already stores the reduced characters in order; join it.","semanticSpec":{"intent":"Return an output derived from the reduced stack state.","doneWhen":"The terminal return consumes the LIFO survivor state.","shouldFailWhen":"This step should fail if the return ignores the reduced stack.","roles":["survivor stack","final string"],"mustProve":["The solution returns a stack-derived reduction outcome."],"mustNotAccept":["Returning the unchanged input."],"proofSnippets":[{"id":"py-remove-adjacent-return-result","language":"python","code":"class Solution:\n    def removeDuplicates(self, s: str) -> str:\n        stack = []\n        for ch in s:\n            if stack and stack[-1] == ch:\n                stack.pop()\n            else:\n                stack.append(ch)\n        return ''.join(stack)"}]}}],"slides":[{"id":"the-task","kind":"info","chapter":"The problem","eyebrow":"Read the problem","title":"Cancel every adjacent twin until none are left","workspacePanel":"problem","body":["Scan a string and erase any two equal characters that sit side by side. Keep doing it until no equal neighbors remain, then return what survives.","For \"abbaca\": the \"bb\" goes first, leaving \"aaca\"; now the \"aa\" is adjacent, so it goes too, leaving \"ca\". The answer is \"ca\"."]},{"id":"rescan-brute","kind":"code-trace","chapter":"The problem","eyebrow":"The obvious way","title":"Delete a pair, then start over?","summary":"The direct method: scan left to right for the first equal pair, delete it, and restart the scan from the front because the deletion may have created a new pair. Watch it grind through \"abba\".","workspacePanel":"trace","body":["Find the first index where two neighbors match, cut both out, and rescan from the beginning. Repeat until a full scan finds no pair."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"chars = list(s)\nchanged = True\nwhile changed:\n    changed = False\n    for i in range(len(chars) - 1):\n        if chars[i] == chars[i + 1]:\n            chars.pop(i + 1)\n            chars.pop(i)\n            changed = True\n            break\nreturn chars","steps":[{"id":"find-bb","title":"First scan finds \"bb\" at index 1","codeLine":6,"summary":"s = \"abba\". The scan walks past index 0, then index 1 holds b with b right after it: the first equal pair.","state":{"s":"abba","i":1}},{"id":"delete-bb","title":"Cut \"bb\" out and restart from the front","codeLine":7,"summary":"Removing both b characters leaves \"aa\". The break sends the scan back to index 0, redoing the characters it already cleared.","state":{"s":"aa","i":0}},{"id":"find-aa","title":"Second full scan finds \"aa\"","codeLine":6,"summary":"The fresh scan from the front finds a and a adjacent at index 0. The earlier work of walking the first a is repeated.","state":{"s":"aa","i":0}},{"id":"empty-out","title":"Cut \"aa\" and the string is empty","codeLine":11,"summary":"Removing the last pair leaves \"\". A final scan finds nothing, so the loop ends. Two characters took two whole rescans.","state":{"s":"","i":0}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const chars = Array.from(s);\nlet changed = true;\nwhile (changed) {\n    changed = false;\n    for (let i = 0; i < (chars.length - 1); i++) {\n        if (chars[i] === chars[(i + 1)]) {\n            chars.splice((i + 1), 1)[0];\n            chars.splice(i, 1)[0];\n            changed = true;\n            break;\n        }\n    }\n}\nreturn chars.join(\"\");","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":14},"statementBundles":{"10":{"startLine":10,"endLine":13}},"alternateStyles":{"close-to-source":{"code":"const chars = Array.from(s);\nlet changed = true;\nwhile (changed) {\n    changed = false;\n    for (let i = 0; i < (chars.length - 1); i++) {\n        if (chars[i] === chars[(i + 1)]) {\n            const poppedValue = chars.splice((i + 1), 1)[0];\n            if (poppedValue === undefined) throw new Error(\"IndexError\");\n            const poppedValue2 = chars.splice(i, 1)[0];\n            if (poppedValue2 === undefined) throw new Error(\"IndexError\");\n            changed = true;\n            break;\n        }\n    }\n}\nreturn chars.join(\"\");","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":11,"10":12,"11":16},"statementBundles":{"7":{"startLine":7,"endLine":8},"8":{"startLine":9,"endLine":10},"10":{"startLine":12,"endLine":15}}}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const chars = Array.from(s);\nlet changed = true;\nwhile (changed) {\n    changed = false;\n    for (let i = 0; i < (chars.length - 1); i++) {\n        if (chars[i] === chars[(i + 1)]) {\n            chars.splice((i + 1), 1)[0];\n            chars.splice(i, 1)[0];\n            changed = true;\n            break;\n        }\n    }\n}\nreturn chars.join(\"\");","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":14},"statementBundles":{"10":{"startLine":10,"endLine":13}},"alternateStyles":{"close-to-source":{"code":"const chars = Array.from(s);\nlet changed = true;\nwhile (changed) {\n    changed = false;\n    for (let i = 0; i < (chars.length - 1); i++) {\n        if (chars[i] === chars[(i + 1)]) {\n            const poppedValue = chars.splice((i + 1), 1)[0];\n            if (poppedValue === undefined) throw new Error(\"IndexError\");\n            const poppedValue2 = chars.splice(i, 1)[0];\n            if (poppedValue2 === undefined) throw new Error(\"IndexError\");\n            changed = true;\n            break;\n        }\n    }\n}\nreturn chars.join(\"\");","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":9,"9":11,"10":12,"11":16},"statementBundles":{"7":{"startLine":7,"endLine":8},"8":{"startLine":9,"endLine":10},"10":{"startLine":12,"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()));\nboolean changed = true;\nwhile (changed) {\n    changed = false;\n    for (int i = 0; i < (chars.size() - 1); i++) {\n        if (chars.get(i) == chars.get(i + 1)) {\n            chars.remove(i + 1);\n            chars.remove(i);\n            changed = true;\n            break;\n        }\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":6,"7":7,"8":8,"9":9,"10":10,"11":14},"statementBundles":{"10":{"startLine":10,"endLine":13}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<string> chars = s.Select(ch => ch.ToString()).ToList();\nbool changed = true;\nwhile (changed) {\n    changed = false;\n    for (int i = 0; i < chars.Count - 1; i++) {\n        if (chars[i] == chars[i + 1]) {\n            chars.RemoveAt(i + 1);\n            chars.RemoveAt(i);\n            changed = true;\n            break;\n        }\n    }\n}\nreturn string.Concat(chars);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":14},"statementBundles":{"10":{"startLine":10,"endLine":13}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"string chars = s;\nbool changed = true;\nwhile (changed) {\n    changed = false;\n    for (int i = 0; i < (chars.size() - 1); i++) {\n        if (chars[i] == chars[(i + 1)]) {\n            chars.erase(chars.begin() + (i + 1));\n            chars.erase(chars.begin() + i);\n            changed = true;\n            break;\n        }\n    }\n}\nreturn chars;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":14},"statementBundles":{"10":{"startLine":10,"endLine":13}}}}}},{"id":"restart-waste","kind":"case-probe","chapter":"The problem","eyebrow":"Name the waste","title":"Why does every deletion restart the whole scan?","workspacePanel":"trace","options":[{"id":"cascade-anywhere","label":"Removing a pair makes the two characters that flanked it adjacent, so a brand-new pair can form right at the cut","rationale":"After \"bb\" leaves, the a before it and the a after it become neighbors and may cancel. The naive method rescans everything only because it never tracks where that survivor is, not because the pair could be anywhere.","isCorrect":true},{"id":"length-changed","label":"The string got shorter, so the old indices are meaningless","rationale":"Indices do shift, but a scan that resumed at the cut would still see the new neighbors. The restart is about not trusting where the next pair is, not about index bookkeeping.","isCorrect":false},{"id":"must-finish","label":"You cannot tell a pair formed without reading the whole string again","rationale":"You can: the only characters that newly touch are the two on either side of the cut. The naive method just fails to use that fact, so it pays for a full rescan each time.","isCorrect":false}],"answer":"A deletion makes the characters on either side of the cut adjacent, possibly forming a new pair. The naive method rescans everything because it never tracks where that new neighbor is.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"s":"abba","i":1}}]},"summary":"On \"abba\", cutting \"bb\" forces the scan back to index 0 to re-examine the leading a."},{"id":"who-cancels","kind":"case-probe","chapter":"The idea","eyebrow":"Name the rule","title":"Which earlier character can the current one cancel?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"stack":["a","b"],"stackActive":[1],"s":"abbaca","i":2}}]},"options":[{"id":"most-recent","label":"Only the most recently surviving character, the one it sits right next to","rationale":"Adjacency is what triggers a removal, and the character physically next to the new one is whichever survivor was kept last. The b just arrived touches the surviving b, so they cancel.","isCorrect":true},{"id":"any-equal","label":"Any equal character still left in the string, wherever it is","rationale":"A removal only happens between neighbors. An equal character with other survivors between it and the current one is not adjacent, so it cannot cancel.","isCorrect":false},{"id":"first-survivor","label":"The first character that survived, at the front","rationale":"The front character is the farthest from the one just read. Removals happen at the current boundary, so the newest survivor is the candidate.","isCorrect":false}],"answer":"A character can only cancel the most recent survivor, the one it is adjacent to. Keep survivors newest-last and the only candidate is always the last one kept.","summary":"Reading \"abbaca\" left to right, a and b have survived so far and the second b has just arrived."},{"id":"after-cancel","kind":"case-probe","chapter":"The idea","eyebrow":"Name the rule","title":"After two characters cancel, what is the next character compared against?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"stack":["a"],"stackActive":[0],"s":"abbaca","i":3}}]},"options":[{"id":"reexposed","label":"The survivor that was underneath the cancelled pair, now exposed as the newest again","rationale":"Removing the b pair makes the a kept before them the most recent survivor once more, so the incoming a sits right beside it and cancels too. The cascade happens for free by always comparing against the last survivor.","isCorrect":true},{"id":"nothing-left","label":"Nothing, the cancelled characters leave a gap that must be skipped","rationale":"There is no gap to skip. Once the pair is gone, the characters that flanked it are neighbors, so the earlier survivor is immediately back in play.","isCorrect":false},{"id":"restart-scan","label":"Nothing yet, the scan must restart to find where the new pair formed","rationale":"Restarting is the slow method this avoids. The survivor beneath is already exposed on top, so the next character meets it in place with no second scan.","isCorrect":false}],"answer":"The survivor beneath the cancelled pair becomes the newest again, so the incoming a meets the earlier a and cancels. Always comparing against the last survivor makes cascades resolve in a single pass.","summary":"The two b characters in \"abbaca\" just cancelled. The next character, a, is about to be read with only the leading a still surviving."},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it move","title":"Keep a stack of survivors","workspacePanel":"visualizer","body":["Walk the string once, holding the surviving characters with the newest on top. Each new character is checked against the top: equal means they cancel, so pop; different means it survives, so push.","The first two characters of \"abbaca\", a then b, have nothing to cancel, so the stack already holds a and b. Watch the rest fall out, including the cascade, without a single restart."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"stack":["a","b"],"stackActive":[1],"s":"abbaca","i":1}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Trace the survivors","title":"Reduce \"abbaca\" in one pass","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"cancel-bb","state":{"s":"abbaca","i":2,"stack":["a","b"],"stackActive":[1]}},{"id":"cascade-a","state":{"s":"abbaca","i":3,"stack":[],"stackActive":[]}},{"id":"push-c","state":{"s":"abbaca","i":4,"stack":["c"],"stackActive":[0]}},{"id":"push-final-a","state":{"s":"abbaca","i":5,"stack":["c","a"],"stackActive":[1]}}]},"beats":[{"id":"cancel-bb","title":"The stack holds a, b and the second b arrives. What happens?","summary":"The newest survivor is b.","prompt":"Reading index 2 of \"abbaca\", the character is b.","options":[{"id":"pop-b","label":"b equals the top, so pop it and keep neither copy","rationale":"Two equal neighbors cancel, and the top b is the neighbor. Popping removes the pair and leaves a as the lone survivor.","isCorrect":true},{"id":"push-b","label":"Push the b as a new survivor","rationale":"Pushing would keep both b characters, but equal neighbors are supposed to disappear together, not stack up.","isCorrect":false},{"id":"pop-all","label":"Clear the whole stack since a duplicate appeared","rationale":"Only the matching pair cancels. The a underneath did not match anything yet, so it stays.","isCorrect":false}],"answer":"b matches the top, so pop. The pair vanishes and the stack is left holding just a."},{"id":"cascade-a","title":"With only a on the stack, the next character a arrives. What happens?","summary":"The b pair already cleared.","prompt":"Index 3 of \"abbaca\" is a, and a is on top.","options":[{"id":"cascade-pop","label":"a equals the exposed top, so pop, emptying the stack","rationale":"Removing the b pair left a as the newest survivor, so this a is its neighbor and they cancel. The cascade resolves with no extra scan.","isCorrect":true},{"id":"push-after-gap","label":"Push the a, since the character it followed was b","rationale":"The b it followed is already gone. The survivor now on top is a, so the incoming a cancels it rather than being kept.","isCorrect":false},{"id":"no-op","label":"Skip it, the stack is too short to compare","rationale":"A stack with one entry still has a top to check. Here that top is a, so the incoming a cancels it.","isCorrect":false}],"answer":"a matches the re-exposed top, so pop. The stack is now empty, and the cascade happened inside the same single pass."},{"id":"push-c","title":"The stack is empty and c arrives. What happens?","summary":"Nothing is waiting to cancel.","prompt":"Index 4 of \"abbaca\" is c with an empty stack.","options":[{"id":"push-c-ans","label":"Push c as a new survivor","rationale":"With no top to compare against, c cannot cancel anything, so it survives and becomes the newest entry.","isCorrect":true},{"id":"skip-empty","label":"Discard c because the stack is empty","rationale":"An empty stack means c has no partner to cancel with, which is a reason to keep it, not drop it.","isCorrect":false},{"id":"restart","label":"Restart the scan from the front","rationale":"The single pass never restarts. c is simply pushed and the walk continues forward.","isCorrect":false}],"answer":"An empty stack has no top, so c cannot cancel and is pushed. The stack now holds c."},{"id":"push-final-a","title":"c is on top and the final a arrives. What is the result?","summary":"The last character of the string.","prompt":"Index 5 of \"abbaca\" is a, with c on top.","options":[{"id":"push-a-result","label":"a differs from c, so push it; the surviving stack reads \"ca\"","rationale":"a and c are not equal, so nothing cancels and a is pushed. The stack, bottom to top, spells the answer \"ca\".","isCorrect":true},{"id":"pop-c","label":"Pop c since another character arrived","rationale":"A pop only happens when the new character equals the top. a does not equal c, so c stays.","isCorrect":false},{"id":"wrong-final","label":"The result is \"aca\", the leftover characters in order","rationale":"The two cancellations already removed the b pair and one a pair. Only c and the final a survive, giving \"ca\".","isCorrect":false}],"answer":"a differs from c, so it is pushed. The stack holds c then a, and joining it gives \"ca\"."}]},{"id":"raw-neighbor-pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","title":"Could comparing against the previous input character work?","workspacePanel":"trace","summary":"A scan can compare each character with the one before it in the original string. That removes the obvious side-by-side pairs every test with no cascade passes. But the raw previous character does not change when a pair is deleted, so it stops tracking which survivor is really adjacent. Watch it run \"abba\".","pitfall":"The code below remembers the previous input character in prev and cancels when the current character equals prev, instead of comparing against the current survivor on top.","whyItMatters":"On \"abba\", after the b pair pops, the final a should meet the surviving a and cancel to \"\". But prev still holds b, so the test fails and a is kept, returning \"aa\" instead of \"\". The fix is to compare against the live top, which the deletion actually updates.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"out = [s[0]]\nprev = s[0]\nfor i in range(1, len(s)):\n    ch = s[i]\n    if ch == prev:\n        out.pop()\n    else:\n        out.append(ch)\n    prev = ch\nreturn out","steps":[{"id":"seed-a","title":"The first a seeds the survivors and prev","codeLine":1,"summary":"s = \"abba\". The leading a is placed as the first survivor and prev is set to a.","state":{"s":"abba","i":0,"stack":["a"],"stackActive":[0],"prev":"a"}},{"id":"push-b","title":"b differs from prev a, so it is pushed","codeLine":8,"summary":"At index 1, ch is b and prev is a: the equality test is false, so the else branch pushes b.","state":{"s":"abba","i":1,"stack":["a","b"],"stackActive":[1],"prev":"b"}},{"id":"pop-b","title":"Second b matches prev and pops","codeLine":6,"summary":"At index 2, ch is b and prev is b: equal, so a pop removes the top b. So far it tracks the survivors.","state":{"s":"abba","i":2,"stack":["a"],"stackActive":[0],"prev":"b"}},{"id":"wrong-push","title":"The final a checks against prev b and is wrongly kept","codeLine":8,"summary":"At index 3, ch is a but prev is still b, so the test fails and a is pushed. The live top is a, which should have cancelled.","state":{"s":"abba","i":3,"stack":["a","a"],"stackActive":[1],"prev":"a"}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const out = [s[0]];\nlet prev = s[0];\nfor (let i = 1; i < s.length; i++) {\n    const ch = s[i];\n    if (ch === prev) {\n        out.pop();\n    } else {\n        out.push(ch);\n    }\n    prev = ch;\n}\nreturn out.join(\"\");","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":12},"statementBundles":{"8":{"startLine":8,"endLine":9},"9":{"startLine":10,"endLine":11}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const out = [s[0]];\nlet prev = s[0];\nfor (let i = 1; i < s.length; i++) {\n    const ch = s[i];\n    if (ch === prev) {\n        out.pop();\n    } else {\n        out.push(ch);\n    }\n    prev = ch;\n}\nreturn out.join(\"\");","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":12},"statementBundles":{"8":{"startLine":8,"endLine":9},"9":{"startLine":10,"endLine":11}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Character> out = new ArrayList<>(List.of(s.charAt(0)));\nchar prev = s.charAt(0);\nfor (int i = 1; i < s.length(); i++) {\n    char ch = s.charAt(i);\n    if (ch == prev) {\n        out.remove(out.size() - 1);\n    } else {\n        out.add(ch);\n    }\n    prev = String.valueOf(ch).charAt(0);\n}\nreturn out.stream().map(String::valueOf).collect(java.util.stream.Collectors.joining());","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":12},"statementBundles":{"8":{"startLine":8,"endLine":9},"9":{"startLine":10,"endLine":11}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<char> out_ = new() { s[0] };\nchar prev = s[0];\nfor (int i = 1; i < s.Length; i++) {\n    char ch = s[i];\n    if (ch == prev) {\n        out_.RemoveAt(out_.Count - 1);\n    } else {\n        out_.Add(ch);\n    }\n    prev = ch;\n}\nreturn new string(out_.ToArray());","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":12},"statementBundles":{"8":{"startLine":8,"endLine":9},"9":{"startLine":10,"endLine":11}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"string out{s[0]};\nchar prev = s[0];\nfor (int i = 1; i < s.size(); i++) {\n    char ch = s[i];\n    if (ch == prev) {\n        out.pop_back();\n    } else {\n        out.push_back(ch);\n    }\n    prev = ch;\n}\nreturn out;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":12},"statementBundles":{"8":{"startLine":8,"endLine":9},"9":{"startLine":10,"endLine":11}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["The stack reduced \"abbaca\" to \"ca\" and caught the cascade in \"abba\". The inputs that stress a survivor stack are the shortest ones and the ones that empty it out.","Two are worth a look before coding: a single character with nothing beside it, and a string where every character finds a partner."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"stack":["c","a"],"stackActive":[1],"s":"abbaca","i":5}}]}},{"id":"single-char-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Force a decision","title":"What does a single character return?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"stack":["a"],"stackActive":[0],"s":"a","i":0}}]},"options":[{"id":"returns-a","label":"\"a\", because it never finds an equal neighbor to cancel with","rationale":"The lone a is pushed onto an empty stack and nothing follows it, so it survives and joining the stack returns \"a\". No special case is needed.","isCorrect":true},{"id":"empty-single","label":"An empty string, since there is no pair to keep","rationale":"A character only disappears when it cancels a twin. With no neighbor, the a is never removed, so the result is \"a\", not \"\".","isCorrect":false},{"id":"needs-guard","label":"It needs a length check before the scan","rationale":"The scan handles one character cleanly: push, then finish. Adding a guard would only repeat the answer the normal path already gives.","isCorrect":false}],"answer":"\"a\". A character with no equal neighbor is pushed and never cancelled, so the stack returns it unchanged.","summary":"s = \"a\", one character with nothing beside it."},{"id":"all-cancel-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Force a decision","title":"What comes back when everything cancels?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"stack":[],"s":"aaaa","i":3}}]},"options":[{"id":"empty-string","label":"The empty string, from joining an empty stack","rationale":"Each a pops the a before it, so the four characters cancel in two pairs and the stack is empty. Joining an empty stack yields \"\", which is the correct answer.","isCorrect":true},{"id":"crash-empty","label":"A pop on the empty stack fails at the end","rationale":"Pops only happen while the stack has a matching top. Once it is empty the scan simply finishes; there is no dangling pop to fail.","isCorrect":false},{"id":"last-a","label":"A single \"a\" left over","rationale":"Four characters form two complete pairs with nothing left. An odd run would leave one survivor, but \"aaaa\" cancels exactly.","isCorrect":false}],"answer":"The empty string. All four characters cancel in pairs, leaving an empty stack, and joining it returns \"\".","summary":"s = \"aaaa\", read left to right."},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"The live top settles every cancellation, including the cascades.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state","state":{"stack":[],"s":"abbaca","i":0}}]},"body":["Walk the string once with a stack of survivors. For each character, check it against the top: cancel the pair when they match, otherwise keep the new character as the newest survivor.","Because every check reads the live top, a deletion re-exposes the survivor beneath it, so cascades resolve as you go. At the end the stack holds the reduced characters in order; turn it back into a string."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the survivor stack","eyebrow":"Code the rule","summary":"Build the survivor stack: start empty, pop the top on a matching adjacent character, push non-matching characters, and join the survivors.","workspacePanel":"code","checkpoints":[{"id":"init-stack","title":"Start a survivor stack","description":"Create an empty stack to hold the characters that have not been removed.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"initializes_empty_stack","scope":"init-stack","readMode":"stack-value-query-v1"}]},"commonMistakes":["Trying to mutate the input string in place","Keeping only the previous raw input character instead of all survivors"],"hint":"The stack should begin empty before scanning `s`.","semanticSpec":{"intent":"Initialize LIFO state for surviving characters.","doneWhen":"An empty stack-like collection exists before the input scan.","shouldFailWhen":"This step should fail if no LIFO state is initialized.","roles":["survivor stack"],"mustProve":["The solution initializes an empty stack."],"mustNotAccept":["Only a scalar previous-character variable."],"proofSnippets":[{"id":"py-remove-adjacent-init-stack-chapter","language":"python","code":"class Solution:\n    def removeDuplicates(self, s: str) -> str:\n        stack = []"}]}},{"id":"scan-string","title":"Scan the input string","description":"Visit each character in order so removals follow the original adjacency order.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"scans_input_sequence","scope":"main-loop","readMode":"stack-value-query-v1"}]},"commonMistakes":["Skipping characters after a pop","Sorting the characters before processing"],"hint":"Process `s` from left to right.","semanticSpec":{"intent":"Scan the source string once in input order.","doneWhen":"The solution loops over the input string.","shouldFailWhen":"This step should fail if the input sequence is not scanned.","roles":["input string","current character"],"mustProve":["The solution scans the input sequence."],"mustNotAccept":["Only handling a fixed number of characters."],"proofSnippets":[{"id":"py-remove-adjacent-scan-string-chapter","language":"python","code":"class Solution:\n    def removeDuplicates(self, s: str) -> str:\n        stack = []\n        for ch in s:\n            pass"}]}},{"id":"duplicate-check","title":"Compare against the stack top","description":"When the stack is non-empty, compare the current character with the most recent survivor.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"branches_on_reduction_token","scope":"operator-branch","readMode":"stack-value-query-v1"}]},"commonMistakes":["Comparing against the previous input index after it may have been removed","Popping without checking that the stack is non-empty"],"hint":"The duplicate test should read the top of the survivor stack.","semanticSpec":{"intent":"Branch on whether the current character cancels with the stack top.","doneWhen":"The scan condition reads both current character state and stack state.","shouldFailWhen":"This step should fail if the stack top is not part of the branch.","roles":["current character","survivor stack top"],"mustProve":["The solution branches on stack reduction state."],"mustNotAccept":["A branch that ignores the stack top."],"proofSnippets":[{"id":"py-remove-adjacent-duplicate-check-chapter","language":"python","code":"class Solution:\n    def removeDuplicates(self, s: str) -> str:\n        stack = []\n        for ch in s:\n            if stack and stack[-1] == ch:\n                pass"}]}},{"id":"pop-duplicate","title":"Remove matching survivors","description":"If the current character matches the stack top, pop that survivor instead of keeping either copy.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"pops_resolved_stack_entry","scope":"pop-entry","readMode":"stack-value-query-v1"}]},"commonMistakes":["Pushing the duplicate character after popping","Removing the wrong end of the survivor collection"],"hint":"A matching pair disappears, so pop the stack top and do not push the current character.","semanticSpec":{"intent":"Pop the stack entry resolved by the current duplicate.","doneWhen":"The duplicate branch removes the LIFO entry.","shouldFailWhen":"This step should fail if duplicates are detected but no stack entry is popped.","roles":["survivor stack"],"mustProve":["The solution pops a resolved stack entry."],"mustNotAccept":["Leaving the duplicate survivor on the stack."],"proofSnippets":[{"id":"py-remove-adjacent-pop-duplicate-chapter","language":"python","code":"class Solution:\n    def removeDuplicates(self, s: str) -> str:\n        stack = []\n        for ch in s:\n            if stack and stack[-1] == ch:\n                stack.pop()"}]}},{"id":"push-survivor","title":"Push non-duplicates","description":"If the current character does not cancel, push it as the newest survivor.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"pushes_current_token_value","scope":"push-value","readMode":"stack-value-query-v1"}]},"commonMistakes":["Appending every character before checking for cancellation","Pushing an index when the output needs characters"],"hint":"The non-duplicate path appends the current character to the stack.","semanticSpec":{"intent":"Push current characters that survive cancellation.","doneWhen":"The current scan value is appended to the LIFO state.","shouldFailWhen":"This step should fail if the scan value is never pushed.","roles":["current character","survivor stack"],"mustProve":["The solution pushes the current token value."],"mustNotAccept":["Only pushing constants or unrelated values."],"proofSnippets":[{"id":"py-remove-adjacent-push-survivor-chapter","language":"python","code":"class Solution:\n    def removeDuplicates(self, s: str) -> str:\n        stack = []\n        for ch in s:\n            if stack and stack[-1] == ch:\n                stack.pop()\n            else:\n                stack.append(ch)"}]}},{"id":"return-result","title":"Return the reduced string","description":"After the scan, convert the survivor stack back into the final string.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"returns_reduced_stack_outcome","scope":"return-answer","readMode":"stack-value-query-v1"}]},"commonMistakes":["Returning the original input string","Returning the stack object instead of a string"],"hint":"The stack already stores the reduced characters in order; join it.","semanticSpec":{"intent":"Return an output derived from the reduced stack state.","doneWhen":"The terminal return consumes the LIFO survivor state.","shouldFailWhen":"This step should fail if the return ignores the reduced stack.","roles":["survivor stack","final string"],"mustProve":["The solution returns a stack-derived reduction outcome."],"mustNotAccept":["Returning the unchanged input."],"proofSnippets":[{"id":"py-remove-adjacent-return-result-chapter","language":"python","code":"class Solution:\n    def removeDuplicates(self, s: str) -> str:\n        stack = []\n        for ch in s:\n            if stack and stack[-1] == ch:\n                stack.pop()\n            else:\n                stack.append(ch)\n        return ''.join(stack)"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","eyebrow":"Take it with you","title":"What to carry forward","summary":"A character can only cancel the most recent survivor, so a stack turns repeated rescans into one pass.","workspacePanel":"code","body":["The leap from delete-and-restart to a survivor stack is comparing against the live top instead of the raw input. The top always names the character that is truly adjacent right now.","That single rule absorbs the cascade: when a pair pops, the survivor underneath is exposed and the next character meets it immediately, with no second scan."],"takeaways":[{"title":"The newest survivor is the only candidate","body":"Adjacency makes the last kept character the one a new character can cancel, so a stack with newest on top is exactly the right memory."},{"title":"Read the current survivor","body":"On \"abba\" the final a must meet the surviving a. Reading the stack top makes the cascade resolve in one pass."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
