{"id":"palindrome-partitioning","title":"Palindrome Partitioning","difficulty":"medium","patterns":["backtracking"],"primaryConcept":"backtracking-subsets","concepts":["backtracking-subsets"],"problemForm":"core","companies":[],"category":"backtracking","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"string","primaryParam":"s","sizeMetric":"length"},"description":"Given a string `s`, return all possible ways to split `s` so that every piece in the split is a palindrome.","examples":[{"input":"s = \"aab\"","output":"[[\"a\",\"a\",\"b\"],[\"aa\",\"b\"]]","explanation":"Both splits use only palindromic pieces."},{"input":"s = \"a\"","output":"[[\"a\"]]","explanation":"A single character is already a palindrome."},{"input":"s = \"abba\"","output":"[[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"bb\",\"a\"],[\"abba\"]]","explanation":"The middle \"bb\" and the whole string \"abba\" create additional valid partitions."}],"constraints":[{"id":"1-len-s-16","text":"1 <= len(s) <= 16","check":{"kind":"sizeRange","target":"s","measure":"stringLength","min":1,"max":16}},{"id":"s-contains-only-lowercase-english-letters","text":"s contains only 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 partition(self, s: str) -> list[list[str]]:\n        # Your code here\n        pass","functionName":"partition","testCases":[{"id":"1","input":{"s":"aab"},"expected":[["a","a","b"],["aa","b"]],"description":"Canonical split with a two-character palindrome prefix."},{"id":"2","input":{"s":"a"},"expected":[["a"]],"description":"Single-character string."},{"id":"3","input":{"s":"efe"},"expected":[["e","f","e"],["efe"]],"description":"Whole string is a palindrome."},{"id":"4","input":{"s":"abba"},"expected":[["a","b","b","a"],["a","bb","a"],["abba"]],"description":"Nested even-length palindromes."},{"id":"5","input":{"s":"aaa"},"expected":[["a","a","a"],["a","aa"],["aa","a"],["aaa"]],"description":"Many overlapping palindrome choices."},{"id":"h1","input":{"s":"ab"},"expected":[["a","b"]]},{"id":"h2","input":{"s":"aba"},"expected":[["a","b","a"],["aba"]]},{"id":"h3","input":{"s":"aabb"},"expected":[["a","a","b","b"],["a","a","bb"],["aa","b","b"],["aa","bb"]]},{"id":"h4","input":{"s":"noon"},"expected":[["n","o","o","n"],["n","oo","n"],["noon"]]},{"id":"h5","input":{"s":"aaab"},"expected":[["a","a","a","b"],["a","aa","b"],["aa","a","b"],["aaa","b"]]},{"id":"topup-racecar","input":{"s":"racecar"},"expected":[["r","a","c","e","c","a","r"],["r","a","cec","a","r"],["r","aceca","r"],["racecar"]],"description":"A full-string palindrome also has nested palindrome partitions."},{"id":"topup-no-long-palindrome","input":{"s":"abc"},"expected":[["a","b","c"]],"description":"No multi-character palindrome leaves only singleton partitions."}],"hints":[{"level":1,"content":"Build one partition from left to right.","revealPattern":false},{"level":2,"content":"At each start index, try every possible end index and keep only palindromic substrings.","revealPattern":true},{"level":3,"content":"Append a valid substring, recurse from the next index, then pop it before trying the next end index.","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":"generate-all-cuts-then-filter","name":"Generate all cuts and filter","summary":"Generate every split pattern first, then reject ones with non-palindrome pieces.","decisionReason":"It forms all 2^(n-1) ways to cut the string and then checks each, doing exponential work on cuts that fail at the very first non-palindrome piece.","complexity":{"time":"O(n * 2^n)","space":"O(n)"},"tradeoffs":["Runs in O(n * 2^n) time and uses O(n) space."],"isOptimal":false},{"id":"backtrack-pal-prefixes","name":"Backtrack over palindromic prefixes","summary":"Try each end index from the current start and recurse only when the substring is a palindrome.","decisionReason":"Only commit a piece when that prefix is a palindrome, then partition the rest the same way, so no doomed cut is ever completed.","complexity":{"time":"O(n * 2^n)","space":"O(n)"},"tradeoffs":["Runs in O(n * 2^n) time and uses O(n) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-result","title":"Initialize the result accumulator","description":"Create the list that will collect complete partitions.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"initializes_result_accumulator","scope":"init-result","readMode":"backtracking-search-value-query-v1"}]},"semanticSpec":{"intent":"Initialize a result accumulator for emitted search solutions.","doneWhen":"A collection is initialized before recursive search begins and is returned or otherwise used as the solution store.","shouldFailWhen":"The code has no collection dedicated to storing complete partitions.","roles":["result accumulator"],"mustProve":["result accumulator initialization"],"mustNotAccept":["temporary path initialization only"],"proofSnippets":[{"id":"py-init-result","language":"python","code":"def partition(s):\n    result = []\n    return result"}]},"hint":"Use one outer result list that every terminal branch can append to."},{"id":"define-backtrack","title":"Define the recursive helper","description":"Create a helper that carries the next start index.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"defines_recursive_helper","scope":"define-backtrack","readMode":"backtracking-search-value-query-v1"}]},"semanticSpec":{"intent":"Define a recursive helper for exploring the choice tree.","doneWhen":"A helper exists and can call itself recursively.","shouldFailWhen":"The code has only flat loops and no recursive search helper.","roles":["recursive helper"],"mustProve":["recursive helper definition","recursive self-call"],"mustNotAccept":["non-recursive helper"],"proofSnippets":[{"id":"py-define-backtrack","language":"python","code":"def partition(s):\n    result = []\n    def backtrack(start):\n        backtrack(start)\n    return result"}]},"hint":"The helper should represent the suffix that still needs to be partitioned."},{"id":"base-case","title":"Emit complete partitions","description":"When the start index reaches the end of the string, append a copy of the current path.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"handles_terminal_solution_case","scope":"base-case","readMode":"backtracking-search-value-query-v1"}]},"semanticSpec":{"intent":"Emit a snapshot of the current search state at a terminal solution branch.","doneWhen":"A completion branch appends a copied path to the result and exits that branch.","shouldFailWhen":"The terminal branch appends the mutable path itself or keeps exploring after a complete split.","roles":["completion condition","path state","result accumulator"],"mustProve":["terminal completion branch","solution snapshot emission","terminal return"],"mustNotAccept":["emitting a live mutable path"],"proofSnippets":[{"id":"py-base-case","language":"python","code":"def partition(s):\n    result = []\n    path = []\n    def backtrack(start):\n        if start == len(s):\n            result.append(path.copy())\n            return\n        backtrack(start)\n    return result"}]},"hint":"Store a snapshot, because the path will be popped while backtracking."},{"id":"loop-choices","title":"Try every substring end","description":"From the current start index, loop over every possible ending index.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"iterates_choice_space","scope":"loop-through-elements","readMode":"backtracking-search-value-query-v1"}]},"semanticSpec":{"intent":"Iterate the candidate choice space from the current boundary.","doneWhen":"The recursive helper contains a choice loop over candidate substring endpoints.","shouldFailWhen":"The helper checks only one fixed endpoint.","roles":["choice loop","choice boundary"],"mustProve":["candidate choice-space iteration"],"mustNotAccept":["single fixed candidate check"],"proofSnippets":[{"id":"py-loop-choices","language":"python","code":"def partition(s):\n    result = []\n    path = []\n    def backtrack(start):\n        if start == len(s):\n            result.append(path.copy())\n            return\n        for end in range(start, len(s)):\n            backtrack(end + 1)\n    return result"}]},"hint":"Each end index represents the next substring choice."},{"id":"candidate-guard","title":"Skip non-palindrome choices","description":"Only explore a substring when it passes the palindrome check.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"guards_candidate_before_choice","scope":"candidate-guard","readMode":"backtracking-search-value-query-v1"}]},"semanticSpec":{"intent":"Guard each candidate choice before extending the search state.","doneWhen":"The choice loop skips or rejects candidates that fail a validity check before recursion continues.","shouldFailWhen":"Every substring is explored without a candidate validity guard.","roles":["candidate guard","choice loop"],"mustProve":["guarded candidate branch"],"mustNotAccept":["unguarded recursive enumeration"],"proofSnippets":[{"id":"py-candidate-guard","language":"python","code":"def partition(s):\n    result = []\n    path = []\n    def is_palindrome(left, right):\n        return True\n    def backtrack(start):\n        if start == len(s):\n            result.append(path.copy())\n            return\n        for end in range(start, len(s)):\n            if not is_palindrome(start, end):\n                continue\n            backtrack(end + 1)\n    return result"}]},"hint":"A non-palindrome substring cannot be part of a valid partition."},{"id":"choose-explore-unchoose","title":"Choose, recurse, and unchoose","description":"Append the valid substring, recurse from the next index, then pop it.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"choose_explore_unchoose","scope":"include-and-backtrack","readMode":"backtracking-search-value-query-v1"}]},"semanticSpec":{"intent":"Mutate search state for a candidate, recurse with progressed state, and roll back the mutation.","doneWhen":"Each valid substring is appended, recursion advances past it, and the substring is removed after recursion.","shouldFailWhen":"The code recurses without undoing the path mutation.","roles":["path state","choice value"],"mustProve":["choice mutation","choice-coupled recursive state progression","post-recursive cleanup"],"mustNotAccept":["missing cleanup"],"proofSnippets":[{"id":"py-choose-explore-unchoose","language":"python","code":"def partition(s):\n    result = []\n    path = []\n    def is_palindrome(left, right):\n        return True\n    def backtrack(start):\n        if start == len(s):\n            result.append(path.copy())\n            return\n        for end in range(start, len(s)):\n            if not is_palindrome(start, end):\n                continue\n            path.append(s[start:end + 1])\n            backtrack(end + 1)\n            path.pop()\n    return result"}]},"hint":"The recursive call should start at end + 1, after the substring you just chose."},{"id":"initial-call","title":"Kick off the search","description":"Start recursion at index 0 with an empty path.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"kicks_off_recursive_search","scope":"initial-call","readMode":"backtracking-search-value-query-v1"}]},"semanticSpec":{"intent":"Call the recursive helper after setting up shared search state.","doneWhen":"The outer function invokes the helper to begin exploring from the start of the input.","shouldFailWhen":"The helper is defined but never called.","roles":["recursive helper","initial state"],"mustProve":["recursive search kickoff"],"mustNotAccept":["unstarted helper"],"proofSnippets":[{"id":"py-initial-call","language":"python","code":"def partition(s):\n    result = []\n    path = []\n    def is_palindrome(left, right):\n        return True\n    def backtrack(start):\n        if start == len(s):\n            result.append(path.copy())\n            return\n        for end in range(start, len(s)):\n            if not is_palindrome(start, end):\n                continue\n            path.append(s[start:end + 1])\n            backtrack(end + 1)\n            path.pop()\n    backtrack(0)"}]},"hint":"The first helper call starts before any characters have been consumed."},{"id":"return-result","title":"Return all partitions","description":"Return the result accumulator after the recursive search completes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"returns_solution_accumulator","scope":"return-result","readMode":"backtracking-search-value-query-v1"}]},"semanticSpec":{"intent":"Return the accumulator that contains every emitted partition.","doneWhen":"The outer function returns the same result collection that terminal branches append to.","shouldFailWhen":"The code returns only the current path or nothing at all.","roles":["result accumulator"],"mustProve":["terminal result return"],"mustNotAccept":["returning path instead of result"],"proofSnippets":[{"id":"py-return-result","language":"python","code":"def partition(s):\n    result = []\n    path = []\n    def is_palindrome(left, right):\n        return True\n    def backtrack(start):\n        if start == len(s):\n            result.append(path.copy())\n            return\n        for end in range(start, len(s)):\n            if not is_palindrome(start, end):\n                continue\n            path.append(s[start:end + 1])\n            backtrack(end + 1)\n            path.pop()\n    backtrack(0)\n    return result"}]},"hint":"Return the outer result list that collected every recorded path."}],"slides":[{"id":"read-the-signal","kind":"info","chapter":"The problem","eyebrow":"Read the problem","title":"Split so every piece reads the same both ways","workspacePanel":"problem","body":["Cut the string into consecutive pieces so that every piece is a palindrome, and list every way to do it.","Every chosen piece must be a palindrome before the remaining suffix is explored. Delaying that check builds complete cut patterns that were already invalid at their first bad piece."]},{"id":"brute-force","kind":"code-trace","chapter":"The problem","eyebrow":"The obvious way","title":"Make every cut, keep the all-palindrome ones","workspacePanel":"trace","summary":"The trace builds all four cut patterns for \"aab\" before the palindrome filter rejects two of them.","body":["Between each neighboring pair of characters, either cut or do not. Build every resulting split, then keep the ones whose every piece is a palindrome."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def partition(s: str) -> list[list[str]]:\n    result: list[list[str]] = []\n    for mask in range(1 << (len(s) - 1)):\n        pieces: list[str] = []\n        start = 0\n        for i in range(len(s) - 1):\n            if mask & (1 << i):\n                pieces.append(s[start:i + 1])\n                start = i + 1\n        pieces.append(s[start:])\n        if all(piece == piece[::-1] for piece in pieces):\n            result.append(pieces)\n    return result","steps":[{"id":"no-cuts","title":"Cut pattern 0 of 4: no cuts","codeLine":11,"summary":"s = \"aab\". With no interior cuts the only piece is \"aab\", which is not a palindrome, so this split is thrown away.","state":{"s":"aab","left":0,"right":2,"stack":["aab"],"stackActive":[0],"labels":{"stack":"pieces"}}},{"id":"cut-after-0","title":"Cut pattern 1 of 4: cut after position 0","codeLine":11,"summary":"Pieces \"a\" and \"ab\". \"ab\" is not a palindrome, so the whole split is thrown away after both pieces were built.","state":{"s":"aab","left":1,"right":2,"stack":["a","ab"],"stackActive":[1],"labels":{"stack":"pieces"}}},{"id":"cut-after-1","title":"Cut pattern 2 of 4: cut after position 1","codeLine":12,"summary":"Pieces \"aa\" and \"b\". Both are palindromes, so this split is kept.","state":{"s":"aab","left":2,"right":2,"stack":["aa","b"],"stackActive":[1],"labels":{"stack":"pieces"}}},{"id":"cut-both","title":"Cut pattern 3 of 4: cut after both positions","codeLine":12,"summary":"Pieces \"a\", \"a\", \"b\". All palindromes, so this split is kept. Four splits built and checked, two survive.","state":{"s":"aab","stack":["a","a","b"],"stackActive":[2],"labels":{"stack":"pieces"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const result = [];\nfor (let mask = 0; mask < (1 << (s.length - 1)); mask++) {\n    const pieces = [];\n    let start = 0;\n    for (let i = 0; i < (s.length - 1); i++) {\n        if (mask & (1 << i)) {\n            pieces.push(s.slice(start, (i + 1)));\n            start = i + 1;\n        }\n    }\n    pieces.push(s.slice(start));\n    let allMatch = true;\n    for (const piece of pieces) {\n        if (!((piece === [...piece].reverse().join(\"\")))) {\n            allMatch = false;\n            break;\n        }\n    }\n    if (allMatch) {\n        result.push(pieces);\n    }\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":11,"11":12,"12":20,"13":23},"statementBundles":{"9":{"startLine":8,"endLine":10},"11":{"startLine":12,"endLine":19},"12":{"startLine":20,"endLine":22}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const result: Array<Array<string>> = [];\nfor (let mask = 0; mask < (1 << (s.length - 1)); mask++) {\n    const pieces: Array<string> = [];\n    let start = 0;\n    for (let i = 0; i < (s.length - 1); i++) {\n        if (mask & (1 << i)) {\n            pieces.push(s.slice(start, (i + 1)));\n            start = i + 1;\n        }\n    }\n    pieces.push(s.slice(start));\n    let allMatch = true;\n    for (const piece of pieces) {\n        if (!((piece === [...piece].reverse().join(\"\")))) {\n            allMatch = false;\n            break;\n        }\n    }\n    if (allMatch) {\n        result.push(pieces);\n    }\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":11,"11":12,"12":20,"13":23},"statementBundles":{"9":{"startLine":8,"endLine":10},"11":{"startLine":12,"endLine":19},"12":{"startLine":20,"endLine":22}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<List<String>> result = new ArrayList<>();\nfor (int mask = 0; mask < (1 << (s.length() - 1)); mask++) {\n    List<String> pieces = new ArrayList<>();\n    int start = 0;\n    for (int i = 0; i < (s.length() - 1); i++) {\n        if ((mask & (1 << i)) != 0) {\n            pieces.add(s.substring(start, (i + 1)));\n            start = i + 1;\n        }\n    }\n    pieces.add(s.substring(start, s.length()));\n    boolean allMatch = true;\n    for (String piece : pieces) {\n        if (!(Objects.equals(piece, new StringBuilder(String.valueOf(piece)).reverse().toString()))) {\n            allMatch = false;\n            break;\n        }\n    }\n    if (allMatch) {\n        result.add(pieces);\n    }\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":11,"11":12,"12":20,"13":23},"statementBundles":{"9":{"startLine":8,"endLine":10},"11":{"startLine":12,"endLine":19},"12":{"startLine":20,"endLine":22}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<List<string>> result = new();\nfor (int mask = 0; mask < 1 << s.Length - 1; mask++) {\n    List<string> pieces = new();\n    int start = 0;\n    for (int i = 0; i < s.Length - 1; i++) {\n        if ((mask & 1 << i) != 0) {\n            pieces.Add(s.Substring(start, (i + 1) - (start)));\n            start = i + 1;\n        }\n    }\n    pieces.Add(s.Substring(start, (s.Length) - (start)));\n    bool allMatch = true;\n    foreach (string piece in pieces) {\n        if (!(piece == new string(piece.Reverse().ToArray()))) {\n            allMatch = false;\n            break;\n        }\n    }\n    if (allMatch) {\n        result.Add(pieces);\n    }\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":11,"11":12,"12":20,"13":23},"statementBundles":{"9":{"startLine":8,"endLine":10},"11":{"startLine":12,"endLine":19},"12":{"startLine":20,"endLine":22}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<vector<string>> result;\nfor (int mask = 0; mask < (1 << (s.size() - 1)); mask++) {\n    vector<string> pieces;\n    int start = 0;\n    for (int i = 0; i < (s.size() - 1); i++) {\n        if (mask & (1 << i)) {\n            pieces.push_back(string(s.begin() + start, s.begin() + (i + 1)));\n            start = i + 1;\n        }\n    }\n    pieces.push_back(string(s.begin() + start, s.begin() + s.size()));\n    bool all_match = true;\n    for (string piece : pieces) {\n        string comparison = piece;\n        reverse(comparison.begin(), comparison.end());\n        if (!(piece == comparison)) {\n            all_match = false;\n            break;\n        }\n    }\n    if (all_match) {\n        result.push_back(pieces);\n    }\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":11,"11":12,"12":22,"13":25},"statementBundles":{"9":{"startLine":8,"endLine":10},"11":{"startLine":12,"endLine":21},"12":{"startLine":22,"endLine":24}}}}}},{"id":"brute-cost","kind":"case-probe","chapter":"The problem","eyebrow":"Count the cuts","title":"At the largest allowed length, n = 16, how many cut patterns get built before any are filtered?","workspacePanel":"trace","summary":"There are 15 gaps between the 16 characters, each cut or not.","options":[{"id":"exp","label":"2^15 patterns, about 32,000, every one fully built before the palindrome filter runs","rationale":"Each of the 15 interior gaps is an independent cut-or-not choice, so the loop forms 2^15 splits and checks each, even the ones that fail on their first piece.","isCorrect":true},{"id":"linear","label":"About 16, one per character","rationale":"The choices are at the gaps and they combine, so the count is exponential in the gaps, not linear in the characters."},{"id":"squared","label":"About 16 squared, one per pair of positions","rationale":"Each gap is an independent on/off choice and they multiply, giving 2^15, far more than the count of position pairs."}],"answer":"2^15 cut patterns, around 32,000. Every gap is an independent choice, so the patterns multiply, and each is built in full before the filter ever looks at it."},{"id":"waste-probe","kind":"case-probe","chapter":"The problem","eyebrow":"Name the waste","title":"A split that starts with the piece \"ab\" is built out fully before being rejected. What was already known?","workspacePanel":"visualizer","summary":"The cut pattern took s[1..2], \"ab\", as one of its pieces.","options":[{"id":"doomed","label":"It was doomed the moment \"ab\" was chosen; that piece is not a palindrome, so no later cuts can rescue the split","rationale":"Once one piece fails the palindrome test the whole split is invalid, yet the brute force still finishes cutting the rest before checking.","isCorrect":true},{"id":"order","label":"The pieces were in the wrong order","rationale":"Order is fixed by the string; the defect is that \"ab\" itself is not a palindrome."},{"id":"nothing","label":"Nothing; you must finish a split to judge it","rationale":"You can judge a prefix: the instant a chosen piece is not a palindrome, every split built on it is dead."}],"answer":"It was doomed when \"ab\" was taken. A single non-palindrome piece invalidates the whole split, so the rest of the cutting is wasted work.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"doomed","state":{"s":"aab","left":1,"right":2,"stack":["a"],"stackActive":[0],"labels":{"stack":"path"}}}]}},{"id":"palindrome-prefix","kind":"case-probe","chapter":"The idea","eyebrow":"Find the rule","title":"Cutting left to right, when can you commit to a first piece?","workspacePanel":"visualizer","summary":"You are choosing the first cut in \"aab\".","options":[{"id":"pal-only","label":"Only when the prefix up to the cut is itself a palindrome","rationale":"Every piece must be a palindrome, so committing a non-palindrome prefix can never lead anywhere; checking before you recurse prunes the dead branch immediately.","isCorrect":true},{"id":"any","label":"Any prefix; check the pieces at the end","rationale":"That is the brute force; testing the prefix before committing skips every doomed split before it is built."},{"id":"shortest","label":"Only the single-character prefix","rationale":"Longer palindrome prefixes like \"aa\" are valid first pieces too; restricting to length one would miss splits."}],"answer":"Only when the prefix is a palindrome. A piece that fails the test can never be part of a valid split, so checking first prunes the whole branch.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"prefix-state","state":{"s":"aab","left":0,"right":1,"stack":[],"labels":{"stack":"path"}}}]}},{"id":"recurse-rest","kind":"case-probe","chapter":"The idea","eyebrow":"Find the subproblem","title":"After taking a palindrome first piece, what is left to solve?","workspacePanel":"visualizer","summary":"You committed \"aa\" as the first piece of \"aab\".","options":[{"id":"same","label":"Partition the remaining suffix the same way, starting just past the piece","rationale":"Once a palindrome prefix is fixed, the rest of the string is an identical sub-problem, so the search recurses from the character after the piece.","isCorrect":true},{"id":"restart","label":"Re-cut the whole string from the start","rationale":"The prefix is already committed; only the suffix after it still needs partitioning."},{"id":"done","label":"Nothing; one palindrome piece is enough","rationale":"The whole string must be covered, so the suffix after the piece still has to be split into palindromes."}],"answer":"Partition the suffix the same way. A committed palindrome prefix leaves an identical, shorter problem starting right after it.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"recurse-state","state":{"s":"aab","left":2,"right":2,"stack":["aa"],"stackActive":[0],"labels":{"stack":"path"}}}]}},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","eyebrow":"Pick the approach","title":"Which shape should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"s":"aab","left":0,"right":0,"stack":[],"labels":{"stack":"path"}}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it move","title":"Take a palindrome piece, partition the rest","workspacePanel":"visualizer","body":["From each position, try every prefix that is a palindrome as the next piece; commit it, partition what remains, then take it back to try a longer prefix.","Watch \"aab\" split into [\"a\", \"a\", \"b\"] and then [\"aa\", \"b\"], with the non-palindrome \"ab\" and \"aab\" never committed."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"s":"aab","left":0,"right":0,"stack":[],"labels":{"stack":"path"}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Split the string","title":"Partition \"aab\"","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"first-a","state":{"s":"aab","left":0,"right":0,"stack":[],"labels":{"stack":"path"}}},{"id":"second-a","state":{"s":"aab","left":1,"right":1,"stack":["a"],"stackActive":[0],"labels":{"stack":"path"}}},{"id":"record-aab","state":{"s":"aab","stack":["a","a","b"],"stackActive":[2],"labels":{"stack":"path"}}},{"id":"longer-aa","state":{"s":"aab","left":0,"right":1,"stack":[],"labels":{"stack":"path"}}},{"id":"record-aa-b","state":{"s":"aab","stack":["aa","b"],"stackActive":[1],"labels":{"stack":"path"}}}]},"beats":[{"id":"first-a","title":"From position 0, the shortest prefix is \"a\". Can it be the first piece?","summary":"The candidate window covers position 0 only.","options":[{"id":"yes","label":"Yes: \"a\" is a palindrome, so commit it and partition the rest","rationale":"Any single character reads the same both ways, so \"a\" is a legal first piece; the search commits it and recurses from position 1.","isCorrect":true},{"id":"no","label":"No, one character is too short","rationale":"A single character is a valid palindrome and a valid piece; length is not the constraint."},{"id":"maybe","label":"Only if the next piece is also \"a\"","rationale":"Each piece is judged on its own; \"a\" is a palindrome regardless of what follows."}],"answer":"Yes. \"a\" is a palindrome, so it is committed as the first piece and the search partitions the suffix \"ab\"."},{"id":"second-a","title":"With \"a\" committed, position 1 offers \"a\" again. Then?","summary":"The window sits on position 1, the second character.","options":[{"id":"take","label":"Commit the second \"a\" and partition what is left, \"b\"","rationale":"The second \"a\" is also a palindrome, so it becomes the next piece and the search recurses on the final \"b\".","isCorrect":true},{"id":"skip","label":"Skip it, one \"a\" is enough","rationale":"The whole string must be covered; the suffix \"ab\" still needs splitting, starting with this \"a\"."},{"id":"merge","label":"Merge it with the first \"a\"","rationale":"The first piece is already committed; this is a separate piece chosen from position 1."}],"answer":"Commit it. The second \"a\" is a palindrome, so it is the next piece, leaving \"b\" to partition."},{"id":"record-aab","title":"The final \"b\" is a palindrome too, completing [\"a\", \"a\", \"b\"]. What now?","summary":"The path \"a\", \"a\", \"b\" now covers every character.","options":[{"id":"record","label":"Record [\"a\", \"a\", \"b\"] and back up to try a longer first piece","rationale":"The whole string is now split into palindromes, so the split is saved; the search then undoes its pieces to explore alternatives like a longer first piece.","isCorrect":true},{"id":"stop","label":"Stop, a valid split is found","rationale":"Other splits remain, such as [\"aa\", \"b\"]; the search backtracks rather than stopping."},{"id":"extend","label":"Keep cutting \"b\" further","rationale":"\"b\" is the last character; there is nothing left to cut. The split is recorded and the search backs up."}],"answer":"Record it and backtrack. The string is fully split into palindromes, so it is saved before the search returns to try a longer first piece."},{"id":"longer-aa","title":"Unwinding to position 0, the next prefix to try is \"aa\". Is it a legal piece?","summary":"Back at position 0, the window now spans the first two characters.","options":[{"id":"yes","label":"Yes: \"aa\" is a palindrome, so commit it and partition \"b\"","rationale":"\"aa\" reads the same both ways, so it is a valid longer first piece; the search commits it and recurses on the remaining \"b\".","isCorrect":true},{"id":"no","label":"No, the first piece was already \"a\"","rationale":"That was a different branch; after undoing it, position 0 is free to try the longer \"aa\"."},{"id":"skip-to-aab","label":"Skip to the full \"aab\"","rationale":"\"aa\" is tried before the full string; and \"aab\" is not a palindrome, so it would be skipped anyway."}],"answer":"Yes. \"aa\" is a palindrome, so it becomes the first piece of a second branch, leaving \"b\" to partition."},{"id":"record-aa-b","title":"\"b\" completes [\"aa\", \"b\"]. And the prefix \"aab\"?","summary":"At position 0, only the full-string prefix \"aab\" is left to try.","options":[{"id":"skipped","label":"\"aab\" is not a palindrome, so it is skipped, leaving exactly [\"a\",\"a\",\"b\"] and [\"aa\",\"b\"]","rationale":"The palindrome guard refuses \"aab\" before recursing, so the search ends with the two valid splits and never builds a doomed one.","isCorrect":true},{"id":"taken","label":"\"aab\" is taken as a single piece","rationale":"\"aab\" reversed is \"baa\", so it is not a palindrome; the guard skips it."},{"id":"more","label":"More splits are still found","rationale":"For \"aab\" there are exactly two palindrome partitions; both are now recorded."}],"answer":"\"aab\" is skipped, since it is not a palindrome. The search ends with the two valid splits, having never committed a non-palindrome piece."}]},{"id":"no-guard-pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","workspacePanel":"trace","title":"Do you really need to take the piece back out?","summary":"The palindrome guard is in place, so only valid pieces get committed. If the recursive call returns without popping the piece, the next end index starts with stale path state. Watch what the first branch leaves behind when the second one starts.","pitfall":"The code below guards every piece but never removes it from the path after the recursive call returns.","whyItMatters":"Without the pop, a piece committed in one branch stays on the path when the search backs up. On \"aab\" the first branch leaves \"a\", \"a\", \"b\" on the path, so when position 0 tries the longer piece \"aa\", it records \"a\", \"a\", \"b\", \"aa\", \"b\" instead of \"aa\", \"b\". Undoing each choice after recursing is what keeps sibling branches independent.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def partition(s: str) -> list[list[str]]:\n    result: list[list[str]] = []\n    path: list[str] = []\n\n    def is_palindrome(left: int, right: int) -> bool:\n        value = s[left:right + 1]\n        return value == value[::-1]\n\n    def piece(left: int, right: int) -> str:\n        return s[left:right + 1]\n\n    def backtrack(start: int) -> None:\n        if start == len(s):\n            result.append(list(path))\n            return\n        end = start\n        while end < len(s):\n            if is_palindrome(start, end):\n                path.append(piece(start, end))\n                backtrack(end + 1)\n            end = end + 1\n    backtrack(0)\n    return result","steps":[{"id":"first-branch","title":"The first branch commits \"a\", \"a\", \"b\" and records it","codeLine":14,"summary":"Every piece passes the guard, so [\"a\", \"a\", \"b\"] is recorded. The path still holds all three pieces.","state":{"s":"aab","stack":["a","a","b"],"stackActive":[2],"labels":{"stack":"path"}}},{"id":"no-pop","title":"Back at position 0, nothing was removed from the path","codeLine":21,"summary":"The loop advances end without popping, so \"a\", \"a\", \"b\" are still on the path as the next piece is tried.","state":{"s":"aab","left":0,"right":1,"stack":["a","a","b"],"stackActive":[],"labels":{"stack":"path"}}},{"id":"corrupted","title":"It records \"a\", \"a\", \"b\", \"aa\", \"b\", a corrupted split","codeLine":14,"summary":"The longer piece \"aa\" is appended onto the leftover path, so the sibling branch is built on stale state and the recorded split is wrong.","state":{"s":"aab","stack":["a","a","b","aa","b"],"stackActive":[4],"labels":{"stack":"path"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const result = [];\nconst path = [];\nfunction isPalindrome(left, right) {\n    const value = s.slice(left, (right + 1));\n    return (value === [...value].reverse().join(\"\"));\n}\nfunction piece(left, right) {\n    return s.slice(left, (right + 1));\n}\nfunction backtrack(start) {\n    if (start == s.length) {\n        result.push(Array.from(path));\n        return;\n    }\n    let end = start;\n    while (end < s.length) {\n        if (isPalindrome(start, end)) {\n            path.push(piece(start, end));\n            backtrack((end + 1));\n        }\n        end = end + 1;\n    }\n}\nbacktrack(0);\nreturn result;","lineMap":{"2":1,"3":2,"6":4,"7":5,"10":8,"13":11,"14":12,"15":13,"16":15,"17":16,"18":17,"19":18,"20":19,"21":21,"22":24,"23":25},"statementBundles":{"3":{"startLine":2,"endLine":3},"7":{"startLine":5,"endLine":7},"10":{"startLine":8,"endLine":10},"15":{"startLine":13,"endLine":14},"20":{"startLine":19,"endLine":20},"21":{"startLine":21,"endLine":23}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const result: Array<Array<string>> = [];\nconst path: Array<string> = [];\nfunction isPalindrome(left: number, right: number): boolean {\n    const value = s.slice(left, (right + 1));\n    return (value === [...value].reverse().join(\"\"));\n}\nfunction piece(left: number, right: number): string {\n    return s.slice(left, (right + 1));\n}\nfunction backtrack(start: number): void {\n    if (start == s.length) {\n        result.push(Array.from(path));\n        return;\n    }\n    let end = start;\n    while (end < s.length) {\n        if (isPalindrome(start, end)) {\n            path.push(piece(start, end));\n            backtrack((end + 1));\n        }\n        end = end + 1;\n    }\n}\nbacktrack(0);\nreturn result;","lineMap":{"2":1,"3":2,"6":4,"7":5,"10":8,"13":11,"14":12,"15":13,"16":15,"17":16,"18":17,"19":18,"20":19,"21":21,"22":24,"23":25},"statementBundles":{"3":{"startLine":2,"endLine":3},"7":{"startLine":5,"endLine":7},"10":{"startLine":8,"endLine":10},"15":{"startLine":13,"endLine":14},"20":{"startLine":19,"endLine":20},"21":{"startLine":21,"endLine":23}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<List<string>> result = new();\nList<string> path = new();\nbool IsPalindrome(int left, int right) {\n    string value = s.Substring(left, (right + 1) - (left));\n    return value == new string(value.Reverse().ToArray());\n}\nstring Piece(int left, int right) {\n    return s.Substring(left, (right + 1) - (left));\n    return null;\n}\nvoid Backtrack(int start) {\n    if (start == s.Length) {\n        result.Add(new List<string>(path));\n        return;\n    }\n    int end = start;\n    while (end < s.Length) {\n        if (IsPalindrome(start, end)) {\n            path.Add(Piece(start, end));\n            Backtrack(end + 1);\n        }\n        end = end + 1;\n    }\n}\nBacktrack(0);\nreturn result;","lineMap":{"2":1,"3":2,"6":4,"7":5,"10":8,"13":12,"14":13,"15":14,"16":16,"17":17,"18":18,"19":19,"20":20,"21":22,"22":25,"23":26},"statementBundles":{"3":{"startLine":2,"endLine":3},"7":{"startLine":5,"endLine":7},"10":{"startLine":8,"endLine":11},"15":{"startLine":14,"endLine":15},"20":{"startLine":20,"endLine":21},"21":{"startLine":22,"endLine":24}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<void(int)> backtrack;\n\nvector<vector<string>> result;\nvector<string> path;\nauto is_palindrome = [&]( int left, int right ) -> bool {\n    string value = string(s.begin() + left, s.begin() + (right + 1));\n    string comparison = value;\n    reverse(comparison.begin(), comparison.end());\n    return (value == comparison);\n};\nauto piece = [&]( int left, int right ) -> string {\n    return string(s.begin() + left, s.begin() + (right + 1));\n};\nbacktrack = [&]( int start ) -> void {\n    if (start == s.size()) {\n        result.push_back(path);\n        return;\n    }\n    int end = start;\n    while (end < s.size()) {\n        if (is_palindrome(start, end)) {\n            path.push_back(piece(start, end));\n            backtrack((end + 1));\n        }\n        end = end + 1;\n    }\n};\nbacktrack(0);\nreturn result;","lineMap":{"2":3,"3":4,"6":6,"7":7,"10":12,"13":15,"14":16,"15":17,"16":19,"17":20,"18":21,"19":22,"20":23,"21":25,"22":28,"23":29},"statementBundles":{"3":{"startLine":4,"endLine":5},"7":{"startLine":7,"endLine":11},"10":{"startLine":12,"endLine":14},"15":{"startLine":17,"endLine":18},"20":{"startLine":23,"endLine":24},"21":{"startLine":25,"endLine":27}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static boolean isPalindrome(int left, int right, String s) {\n    String value = s.substring(left, (right + 1));\n    return Objects.equals(value, new StringBuilder(String.valueOf(value)).reverse().toString());\n}\n\nprivate static String piece(int left, int right, String s) {\n    return String.valueOf(s.substring(left, (right + 1)));\n}\n\nprivate static void backtrack(int start, String s, List<List<String>> result, List<String> path) {\n    if (start == s.length()) {\n        result.add(new ArrayList<String>(path));\n        return;\n    }\n    int end = start;\n    while (end < s.length()) {\n        if (isPalindrome(start, end, s)) {\n            path.add(piece(start, end, s));\n            backtrack((end + 1), s, result, path);\n        }\n        end = end + 1;\n    }\n}\n\nList<List<String>> result = new ArrayList<>();\nList<String> path = new ArrayList<>();\nbacktrack(0, s, result, path);\nreturn result;","lineMap":{"2":25,"3":26,"6":2,"7":3,"10":7,"13":11,"14":12,"15":13,"16":15,"17":16,"18":17,"19":18,"20":19,"21":21,"22":27,"23":28},"statementBundles":{"7":{"startLine":3,"endLine":6},"10":{"startLine":7,"endLine":10},"15":{"startLine":13,"endLine":14},"20":{"startLine":19,"endLine":20},"21":{"startLine":21,"endLine":23}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["The palindrome guard produced exactly the valid splits for \"aab\". The inputs that test it sit at the extremes of the branching: the shortest possible string, and a string with no variety at all.","Two are worth a look: a single character, \"a\", and a run of identical letters, \"aaa\"."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"s":"aab","left":0,"right":0,"stack":[],"labels":{"stack":"path"}}}]}},{"id":"single-char-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"For s = \"a\", what is produced?","workspacePanel":"visualizer","summary":"The search starts and ends on the only character.","options":[{"id":"one","label":"[[\"a\"]], a single split","rationale":"\"a\" is a palindrome, so it is committed, the suffix is empty, and [\"a\"] is recorded as the only partition.","isCorrect":true},{"id":"empty","label":"An empty result","rationale":"A single character is itself a valid palindrome piece, so there is exactly one split."},{"id":"two","label":"Two splits","rationale":"With one character there is nowhere else to cut, so only one partition exists."}],"answer":"[[\"a\"]]. The lone character is a palindrome piece, leaving nothing after it, so there is one split.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-state","state":{"s":"a","left":0,"right":0,"stack":["a"],"stackActive":[0],"labels":{"stack":"path"}}}]}},{"id":"all-same-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"For \"aaa\", why are there several splits?","workspacePanel":"visualizer","summary":"The input is \"aaa\".","options":[{"id":"every-prefix","label":"Every prefix of equal letters is a palindrome, so each position can cut in multiple legal ways","rationale":"With all letters the same, \"a\", \"aa\", and \"aaa\" are all palindromes, so the guard never prunes and the splits branch into [\"a\",\"a\",\"a\"], [\"a\",\"aa\"], [\"aa\",\"a\"], [\"aaa\"].","isCorrect":true},{"id":"one","label":"There is still only one split","rationale":"Because \"aa\" and \"aaa\" are also palindromes, longer pieces are legal too, giving several distinct partitions."},{"id":"guard-blocks","label":"The guard blocks most of them","rationale":"The guard passes every equal-letter prefix, so it blocks nothing here; the count comes from all those legal pieces."}],"answer":"Every equal-letter prefix is a palindrome, so the guard prunes nothing and the search finds all four partitions of \"aaa\".","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"all-same-state","state":{"s":"aaa","left":0,"right":2,"stack":[],"labels":{"stack":"path"}}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Turn the rule into code","workspacePanel":"visualizer","summary":"Only palindrome prefixes get committed.","body":["From each position, try each prefix in turn, and commit it as a piece only when it reads the same both ways; then partition the rest from just past it, and take the piece back to try a longer one.","When a branch reaches the end of the string, every piece on the path is a palindrome, so the path is one valid split; record a copy and let the search back up."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"s":"aab","left":0,"right":1,"stack":[],"labels":{"stack":"path"}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the palindrome backtracking","eyebrow":"Code the rule","summary":"The code needs the result list, the start-index helper, the palindrome guard, the choose/recurse/pop sequence, the initial call, and the final return.","workspacePanel":"code","checkpoints":[{"id":"init-result","title":"Initialize the result accumulator","description":"Create the list that will collect complete partitions.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"initializes_result_accumulator","scope":"init-result","readMode":"backtracking-search-value-query-v1"}]},"semanticSpec":{"intent":"Initialize a result accumulator for emitted search solutions.","doneWhen":"A collection is initialized before recursive search begins and is returned or otherwise used as the solution store.","shouldFailWhen":"The code has no collection dedicated to storing complete partitions.","roles":["result accumulator"],"mustProve":["result accumulator initialization"],"mustNotAccept":["temporary path initialization only"],"proofSnippets":[{"id":"py-init-result","language":"python","code":"def partition(s):\n    result = []\n    return result"}]},"hint":"Use one outer result list that every terminal branch can append to."},{"id":"define-backtrack","title":"Define the recursive helper","description":"Create a helper that carries the next start index.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"defines_recursive_helper","scope":"define-backtrack","readMode":"backtracking-search-value-query-v1"}]},"semanticSpec":{"intent":"Define a recursive helper for exploring the choice tree.","doneWhen":"A helper exists and can call itself recursively.","shouldFailWhen":"The code has only flat loops and no recursive search helper.","roles":["recursive helper"],"mustProve":["recursive helper definition","recursive self-call"],"mustNotAccept":["non-recursive helper"],"proofSnippets":[{"id":"py-define-backtrack","language":"python","code":"def partition(s):\n    result = []\n    def backtrack(start):\n        backtrack(start)\n    return result"}]},"hint":"The helper should represent the suffix that still needs to be partitioned."},{"id":"base-case","title":"Emit complete partitions","description":"When the start index reaches the end of the string, append a copy of the current path.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"handles_terminal_solution_case","scope":"base-case","readMode":"backtracking-search-value-query-v1"}]},"semanticSpec":{"intent":"Emit a snapshot of the current search state at a terminal solution branch.","doneWhen":"A completion branch appends a copied path to the result and exits that branch.","shouldFailWhen":"The terminal branch appends the mutable path itself or keeps exploring after a complete split.","roles":["completion condition","path state","result accumulator"],"mustProve":["terminal completion branch","solution snapshot emission","terminal return"],"mustNotAccept":["emitting a live mutable path"],"proofSnippets":[{"id":"py-base-case","language":"python","code":"def partition(s):\n    result = []\n    path = []\n    def backtrack(start):\n        if start == len(s):\n            result.append(path.copy())\n            return\n        backtrack(start)\n    return result"}]},"hint":"Store a snapshot, because the path will be popped while backtracking."},{"id":"loop-choices","title":"Try every substring end","description":"From the current start index, loop over every possible ending index.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"iterates_choice_space","scope":"loop-through-elements","readMode":"backtracking-search-value-query-v1"}]},"semanticSpec":{"intent":"Iterate the candidate choice space from the current boundary.","doneWhen":"The recursive helper contains a choice loop over candidate substring endpoints.","shouldFailWhen":"The helper checks only one fixed endpoint.","roles":["choice loop","choice boundary"],"mustProve":["candidate choice-space iteration"],"mustNotAccept":["single fixed candidate check"],"proofSnippets":[{"id":"py-loop-choices","language":"python","code":"def partition(s):\n    result = []\n    path = []\n    def backtrack(start):\n        if start == len(s):\n            result.append(path.copy())\n            return\n        for end in range(start, len(s)):\n            backtrack(end + 1)\n    return result"}]},"hint":"Each end index represents the next substring choice."},{"id":"candidate-guard","title":"Skip non-palindrome choices","description":"Only explore a substring when it passes the palindrome check.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"guards_candidate_before_choice","scope":"candidate-guard","readMode":"backtracking-search-value-query-v1"}]},"semanticSpec":{"intent":"Guard each candidate choice before extending the search state.","doneWhen":"The choice loop skips or rejects candidates that fail a validity check before recursion continues.","shouldFailWhen":"Every substring is explored without a candidate validity guard.","roles":["candidate guard","choice loop"],"mustProve":["guarded candidate branch"],"mustNotAccept":["unguarded recursive enumeration"],"proofSnippets":[{"id":"py-candidate-guard","language":"python","code":"def partition(s):\n    result = []\n    path = []\n    def is_palindrome(left, right):\n        return True\n    def backtrack(start):\n        if start == len(s):\n            result.append(path.copy())\n            return\n        for end in range(start, len(s)):\n            if not is_palindrome(start, end):\n                continue\n            backtrack(end + 1)\n    return result"}]},"hint":"A non-palindrome substring cannot be part of a valid partition."},{"id":"choose-explore-unchoose","title":"Choose, recurse, and unchoose","description":"Append the valid substring, recurse from the next index, then pop it.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"choose_explore_unchoose","scope":"include-and-backtrack","readMode":"backtracking-search-value-query-v1"}]},"semanticSpec":{"intent":"Mutate search state for a candidate, recurse with progressed state, and roll back the mutation.","doneWhen":"Each valid substring is appended, recursion advances past it, and the substring is removed after recursion.","shouldFailWhen":"The code recurses without undoing the path mutation.","roles":["path state","choice value"],"mustProve":["choice mutation","choice-coupled recursive state progression","post-recursive cleanup"],"mustNotAccept":["missing cleanup"],"proofSnippets":[{"id":"py-choose-explore-unchoose","language":"python","code":"def partition(s):\n    result = []\n    path = []\n    def is_palindrome(left, right):\n        return True\n    def backtrack(start):\n        if start == len(s):\n            result.append(path.copy())\n            return\n        for end in range(start, len(s)):\n            if not is_palindrome(start, end):\n                continue\n            path.append(s[start:end + 1])\n            backtrack(end + 1)\n            path.pop()\n    return result"}]},"hint":"The recursive call should start at end + 1, after the substring you just chose."},{"id":"initial-call","title":"Kick off the search","description":"Start recursion at index 0 with an empty path.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"kicks_off_recursive_search","scope":"initial-call","readMode":"backtracking-search-value-query-v1"}]},"semanticSpec":{"intent":"Call the recursive helper after setting up shared search state.","doneWhen":"The outer function invokes the helper to begin exploring from the start of the input.","shouldFailWhen":"The helper is defined but never called.","roles":["recursive helper","initial state"],"mustProve":["recursive search kickoff"],"mustNotAccept":["unstarted helper"],"proofSnippets":[{"id":"py-initial-call","language":"python","code":"def partition(s):\n    result = []\n    path = []\n    def is_palindrome(left, right):\n        return True\n    def backtrack(start):\n        if start == len(s):\n            result.append(path.copy())\n            return\n        for end in range(start, len(s)):\n            if not is_palindrome(start, end):\n                continue\n            path.append(s[start:end + 1])\n            backtrack(end + 1)\n            path.pop()\n    backtrack(0)"}]},"hint":"The first helper call starts before any characters have been consumed."},{"id":"return-result","title":"Return all partitions","description":"Return the result accumulator after the recursive search completes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"backtracking-search","fact":"returns_solution_accumulator","scope":"return-result","readMode":"backtracking-search-value-query-v1"}]},"semanticSpec":{"intent":"Return the accumulator that contains every emitted partition.","doneWhen":"The outer function returns the same result collection that terminal branches append to.","shouldFailWhen":"The code returns only the current path or nothing at all.","roles":["result accumulator"],"mustProve":["terminal result return"],"mustNotAccept":["returning path instead of result"],"proofSnippets":[{"id":"py-return-result","language":"python","code":"def partition(s):\n    result = []\n    path = []\n    def is_palindrome(left, right):\n        return True\n    def backtrack(start):\n        if start == len(s):\n            result.append(path.copy())\n            return\n        for end in range(start, len(s)):\n            if not is_palindrome(start, end):\n                continue\n            path.append(s[start:end + 1])\n            backtrack(end + 1)\n            path.pop()\n    backtrack(0)\n    return result"}]},"hint":"Return the outer result list that collected every recorded path."}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Commit a piece only when its prefix is a palindrome, then partition the rest the same way, so no doomed split is ever completed.","workspacePanel":"code","body":["The leap from cut-then-filter to backtracking is testing each piece before recursing, so a non-palindrome prefix prunes its whole branch instead of being finished and discarded.","A committed palindrome prefix turns the rest of the string into the same problem, smaller, which is exactly what the recursion solves."],"takeaways":[{"title":"Guard each piece before recursing","body":"Checking the prefix before recursing prunes every split built on a non-palindrome piece before it exists."},{"title":"The suffix is the same problem","body":"Once a palindrome prefix is fixed, partition what remains from just past it, recursing until the string is covered."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"},"timeComplexity":"O(n * 2^n)","spaceComplexity":"O(n)"}
