{"id":"generate-parentheses","title":"Generate Parentheses","difficulty":"medium","patterns":["backtracking"],"primaryConcept":"backtracking-constraint-placement","concepts":["backtracking-constraint-placement"],"problemForm":"core","companies":["Meta","Amazon","Google"],"category":"backtracking","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"scalar","primaryParam":"n","sizeMetric":"scalar","sizes":[2,3,4,6]},"description":"Given `n` pairs of parentheses, generate all combinations of well-formed parentheses.","examples":[{"input":"n = 3","output":"[\"((()))\",\"(()())\",\"(())()\",\"()(())\",\"()()()\"]","explanation":"These are all five valid strings with three pairs."},{"input":"n = 1","output":"[\"()\"]","explanation":"Only one well-formed pair can be built."}],"constraints":[{"id":"1-n-8","text":"1 <= n <= 8","check":{"kind":"valueRange","target":"n","selector":"value","min":1,"max":8}}],"starterCode":"class Solution:\n    def generateParenthesis(self, n: int) -> list[str]:\n        # Your code here\n        pass","functionName":"generateParenthesis","testCases":[{"id":"1","input":{"n":1},"expected":["()"],"description":"Single pair."},{"id":"2","input":{"n":2},"expected":["(())","()()"],"description":"Two valid strings for two pairs."},{"id":"3","input":{"n":3},"expected":["((()))","(()())","(())()","()(())","()()()"],"description":"Canonical Catalan-5 case."},{"id":"h1","input":{"n":4},"description":"First larger Catalan case.","expected":["(((())))","((()()))","((())())","((()))()","(()(()))","(()()())","(()())()","(())(())","(())()()","()((()))","()(()())","()(())()","()()(())","()()()()"]},{"id":"h2","input":{"n":5},"description":"Five pairs force deeper backtracking.","expected":["((((()))))","(((()())))","(((())()))","(((()))())","(((())))()","((()(())))","((()()()))","((()())())","((()()))()","((())(()))","((())()())","((())())()","((()))(())","((()))()()","(()((())))","(()(()()))","(()(())())","(()(()))()","(()()(()))","(()()()())","(()()())()","(()())(())","(()())()()","(())((()))","(())(()())","(())(())()","(())()(())","(())()()()","()(((())))","()((()()))","()((())())","()((()))()","()(()(()))","()(()()())","()(()())()","()(())(())","()(())()()","()()((()))","()()(()())","()()(())()","()()()(())","()()()()()"]}],"hints":[{"level":1,"content":"Build the string one character at a time."},{"level":2,"content":"You can add `(` only while fewer than n opens have been used."},{"level":3,"content":"You can add `)` only while it would not exceed the number of opens."}],"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-filter","name":"Generate all strings then filter","summary":"Create every length-2n string of parentheses and test validity afterward.","decisionReason":"It builds all 2^(2n) strings of brackets and throws away the invalid ones, doing exponential work that is almost all wasted.","complexity":{"time":"O(2^(2n) * n)","space":"O(2n)"},"tradeoffs":["Runs in O(2^(2n) * n) time and uses O(2n) space."],"isOptimal":false},{"id":"guarded-backtracking","name":"Guarded backtracking","summary":"Only add parentheses that can still lead to a valid final string.","decisionReason":"Build only valid prefixes: add an opener while opens remain and a closer only when it closes an earlier opener, so every finished string is already well-formed.","complexity":{"time":"O(Cn * n)","space":"O(Cn * n)"},"tradeoffs":["Runs in O(Cn * n) time and uses O(Cn * n) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-result","title":"Initialize result","description":"Create the list that will collect complete strings.","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 an accumulator for all complete parentheses strings.","doneWhen":"This step is done when the function creates an empty result list before recursion begins.","shouldFailWhen":"This step should fail if complete strings have nowhere persistent to be stored.","roles":["result accumulator","complete strings"],"mustProve":["The result accumulator is initialized before the helper runs."],"mustNotAccept":["Returning only the current path."],"equivalentVariants":["Use any list-like accumulator for completed strings."],"proofSnippets":[{"id":"py-generate-parentheses-init-result","language":"python","code":"class Solution:\n    def generateParenthesis(self, n: int) -> list[str]:\n        result = []\n        return result"}]},"commonMistakes":["Forgetting to collect all complete strings","Using a single string as the only result"],"hint":"The recursive helper should append complete strings into one shared list."},{"id":"base-case","title":"Emit complete path","description":"When the path reaches length 2n, append the completed string and return.","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":"Recognize a complete parentheses string and emit it as a snapshot.","doneWhen":"This step is done when the helper joins or copies the path into result once its length is 2n and returns from that branch.","shouldFailWhen":"This step should fail if complete paths keep recursing or append a mutable path object directly.","roles":["completion condition","path snapshot","terminal return"],"mustProve":["The helper checks for a complete path.","A completed path is emitted and the branch returns."],"mustNotAccept":["Continuing to add parentheses after length 2n."],"equivalentVariants":["Join the path list into a string before appending.","Carry the path as a string and append that string at completion."],"proofSnippets":[{"id":"py-generate-parentheses-base-case","language":"python","code":"class Solution:\n    def generateParenthesis(self, n: int) -> list[str]:\n        result = []\n        def backtrack(path: list[str], open_count: int, close_count: int) -> None:\n            if len(path) == 2 * n:\n                result.append(\"\".join(path))\n                return\n            backtrack(path, open_count, close_count)\n        return result"}]},"commonMistakes":["Appending the mutable path list instead of a string snapshot","Forgetting to return after emitting"],"hint":"A complete string has exactly 2n characters."},{"id":"choice-loop","title":"Loop over choices","description":"Try the two parenthesis choices from each recursive state.","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":"Enumerate possible next characters for the current path.","doneWhen":"This step is done when the helper loops over the open and close parenthesis choices.","shouldFailWhen":"This step should fail if the code only tries one fixed next character.","roles":["choice loop","open choice","close choice"],"mustProve":["The helper iterates over a parenthesis choice space."],"mustNotAccept":["Checking only one candidate character."],"equivalentVariants":["Loop over a two-item choices list.","Use any equivalent choice iteration that considers both parenthesis types."],"proofSnippets":[{"id":"py-generate-parentheses-choice-loop","language":"python","code":"class Solution:\n    def generateParenthesis(self, n: int) -> list[str]:\n        result = []\n        choices = [\"(\", \")\"]\n        def backtrack(path: list[str], open_count: int, close_count: int) -> None:\n            if len(path) == 2 * n:\n                result.append(\"\".join(path))\n                return\n            for choice in choices:\n                backtrack(path, open_count, close_count)\n        return result"}]},"commonMistakes":["Trying only open parentheses first without ever considering close choices","Generating fixed strings instead of branching"],"hint":"Every state can consider `(` and `)`, then guards decide which are legal."},{"id":"candidate-guard","title":"Skip invalid choices","description":"Skip opens after n opens and skip closes that would exceed opens.","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":"Reject any next parenthesis that cannot lead to a valid final string before mutating the path.","doneWhen":"This step is done when the code skips `(` after n opens and skips `)` whenever closes would catch or exceed opens.","shouldFailWhen":"This step should fail if invalid closing parentheses can be appended.","roles":["open count","close count","candidate guard"],"mustProve":["Open choices are bounded by n.","Close choices are bounded by the current open count."],"mustNotAccept":["Allowing more closes than opens.","Allowing more than n opens."],"equivalentVariants":["Use `continue` guards before append.","Use equivalent conditionals that only allow valid choices to reach append."],"proofSnippets":[{"id":"py-generate-parentheses-candidate-guard","language":"python","code":"class Solution:\n    def generateParenthesis(self, n: int) -> list[str]:\n        result = []\n        choices = [\"(\", \")\"]\n        def backtrack(path: list[str], open_count: int, close_count: int) -> None:\n            if len(path) == 2 * n:\n                result.append(\"\".join(path))\n                return\n            for choice in choices:\n                if choice == \"(\" and open_count >= n:\n                    continue\n                if choice == \")\" and close_count >= open_count:\n                    continue\n                backtrack(path, open_count, close_count)\n        return result"}]},"commonMistakes":["Adding a close parenthesis when closes already equal opens","Adding more than n open parentheses"],"hint":"Invalid candidates should be filtered before they touch the path."},{"id":"choose-explore-unchoose","title":"Choose, recurse, unchoose","description":"Append the chosen parenthesis, recurse with updated counts, 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 the path for one choice, recursively explore the branch, then restore the path for the next choice.","doneWhen":"This step is done when each valid choice appends to the path, recurses with the corresponding updated count, and pops the path afterward.","shouldFailWhen":"This step should fail if the code appends without cleanup or recurses without changing counts.","roles":["path mutation","recursive call","rollback cleanup"],"mustProve":["The chosen parenthesis is appended before recursion.","The recursive call advances the matching count.","The append is undone after recursion."],"mustNotAccept":["Missing path cleanup.","Recursing with unchanged open and close counts."],"equivalentVariants":["Use append/pop around recursion.","Use equivalent mutable path operations as long as each branch is restored."],"proofSnippets":[{"id":"py-generate-parentheses-choose-explore-unchoose","language":"python","code":"class Solution:\n    def generateParenthesis(self, n: int) -> list[str]:\n        result = []\n        choices = [\"(\", \")\"]\n        def backtrack(path: list[str], open_count: int, close_count: int) -> None:\n            if len(path) == 2 * n:\n                result.append(\"\".join(path))\n                return\n            for choice in choices:\n                if choice == \"(\" and open_count >= n:\n                    continue\n                if choice == \")\" and close_count >= open_count:\n                    continue\n                path.append(choice)\n                if choice == \"(\":\n                    backtrack(path, open_count + 1, close_count)\n                else:\n                    backtrack(path, open_count, close_count + 1)\n                path.pop()\n        return result"}]},"commonMistakes":["Forgetting to pop the choice","Incrementing the wrong count"],"hint":"After recursion returns, restore the path exactly as it was before the choice."},{"id":"initial-call","title":"Start recursion","description":"Start with an empty path and zero open and close parentheses.","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":"Kick off the recursive search from the empty partial string.","doneWhen":"This step is done when the function calls the helper with an empty path, zero opens, and zero closes.","shouldFailWhen":"This step should fail if the helper is never called or starts from a non-empty invalid path.","roles":["initial helper call","empty path","zero counts"],"mustProve":["The recursive helper is invoked after it is defined."],"mustNotAccept":["Returning before calling the helper."],"equivalentVariants":["Start with an empty list path.","Start with an empty string path if the rest of the implementation is immutable."],"proofSnippets":[{"id":"py-generate-parentheses-initial-call","language":"python","code":"class Solution:\n    def generateParenthesis(self, n: int) -> list[str]:\n        result = []\n        choices = [\"(\", \")\"]\n        def backtrack(path: list[str], open_count: int, close_count: int) -> None:\n            if len(path) == 2 * n:\n                result.append(\"\".join(path))\n                return\n            for choice in choices:\n                if choice == \"(\" and open_count >= n:\n                    continue\n                if choice == \")\" and close_count >= open_count:\n                    continue\n                path.append(choice)\n                if choice == \"(\":\n                    backtrack(path, open_count + 1, close_count)\n                else:\n                    backtrack(path, open_count, close_count + 1)\n                path.pop()\n        backtrack([], 0, 0)"}]},"commonMistakes":["Never invoking the helper","Starting with one parenthesis already in the path"],"hint":"The root of the search tree is the empty path."},{"id":"return-result","title":"Return all strings","description":"Return the accumulator after recursive search finishes.","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 complete list of generated well-formed strings.","doneWhen":"This step is done when the function returns the result accumulator after the initial recursive call.","shouldFailWhen":"This step should fail if the function returns the current path or only the number of strings.","roles":["result accumulator","final return"],"mustProve":["The returned value is the accumulator populated by recursion."],"mustNotAccept":["Returning a count instead of the generated strings."],"equivalentVariants":["Return the shared result list after search completes."],"proofSnippets":[{"id":"py-generate-parentheses-return-result","language":"python","code":"class Solution:\n    def generateParenthesis(self, n: int) -> list[str]:\n        result = []\n        choices = [\"(\", \")\"]\n        def backtrack(path: list[str], open_count: int, close_count: int) -> None:\n            if len(path) == 2 * n:\n                result.append(\"\".join(path))\n                return\n            for choice in choices:\n                if choice == \"(\" and open_count >= n:\n                    continue\n                if choice == \")\" and close_count >= open_count:\n                    continue\n                path.append(choice)\n                if choice == \"(\":\n                    backtrack(path, open_count + 1, close_count)\n                else:\n                    backtrack(path, open_count, close_count + 1)\n                path.pop()\n        backtrack([], 0, 0)\n        return result"}]},"commonMistakes":["Returning the path stack","Returning before recursion fills the result"],"hint":"The result list is the output."}],"slides":[{"id":"read-the-signal","kind":"info","chapter":"The problem","eyebrow":"Read the problem","title":"Every way to balance n pairs","workspacePanel":"problem","body":["Given n pairs of parentheses, list every well-formed arrangement: each opener is matched by a later closer, and no closer ever appears before there is an opener waiting for it.","A partial arrangement can be rejected before it reaches full length: it can never use more than n openers, and its closers can never outnumber its openers."]},{"id":"brute-force","kind":"code-trace","chapter":"The problem","eyebrow":"The obvious way","title":"Build every string, then keep the valid ones","summary":"Generating all 2^(2n) bracket strings and filtering for the well-formed ones gets the right answer, but most of those strings are doomed long before they finish. Watch how much building happens on branches that can never balance.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def generateParenthesis(n: int) -> list[str]:\n    candidates: list[str] = []\n    def is_valid(s: str) -> bool:\n        balance = 0\n        for ch in s:\n            if ch == \"(\":\n                balance += 1\n            else:\n                balance -= 1\n            if balance < 0:\n                return False\n        return balance == 0\n    def build(s: str) -> None:\n        if len(s) == 2 * n:\n            candidates.append(s)\n            return\n        build(s + \"(\")\n        build(s + \")\")\n    build(\"\")\n    return [s for s in candidates if is_valid(s)]","steps":[{"id":"build-first","title":"The first full string is (((( ","codeLine":15,"summary":"n = 2, so every candidate is 4 characters. The recursion adds ( before ), so the first one built is ((((.","state":{"stack":["(","(","(","("],"stackActive":[3],"built":1,"labels":{"stack":"s"}}},{"id":"build-doomed","title":"A string starting with ) is still built in full","codeLine":18,"summary":"build never inspects what it is making, so )((( gets all 4 characters before anything checks it.","state":{"stack":[")","(","(","("],"stackActive":[3],"built":9,"labels":{"stack":"s"}}},{"id":"build-all","title":"All 2^4 = 16 strings now exist","codeLine":19,"summary":"Two choices at each of 4 positions makes 16 candidates, every one constructed to full length.","state":{"stack":[")",")",")",")"],"stackActive":[3],"built":16,"labels":{"stack":"s"}}},{"id":"filter","title":"is_valid keeps only 2 of the 16","codeLine":20,"summary":"Only (()) and ()() are balanced. The other 14 were built in full and immediately thrown away.","state":{"stack":["(","(",")",")"],"stackActive":[3],"built":16,"kept":2,"labels":{"stack":"s"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const candidates = [];\nfunction isValid(s) {\n    let balance = 0;\n    for (const ch of s) {\n        if (ch === \"(\") {\n            balance++;\n        } else {\n            balance--;\n        }\n        if (balance < 0) {\n            return false;\n        }\n    }\n    return (balance === 0);\n}\nfunction build(s) {\n    if (s.length == (2 * n)) {\n        candidates.push(s);\n        return;\n    }\n    build((s + \"(\"));\n    build((s + \")\"));\n}\nbuild(\"\");\nreturn candidates.filter((s) => isValid(s));","lineMap":{"2":1,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":10,"11":11,"12":14,"14":17,"15":18,"16":19,"17":21,"18":22,"19":24,"20":25},"statementBundles":{"2":{"startLine":1,"endLine":2},"9":{"startLine":8,"endLine":9},"11":{"startLine":11,"endLine":13},"12":{"startLine":14,"endLine":16},"16":{"startLine":19,"endLine":20},"18":{"startLine":22,"endLine":23}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const candidates: Array<string> = [];\nfunction isValid(s: string): boolean {\n    let balance = 0;\n    for (const ch of s) {\n        if (ch === \"(\") {\n            balance++;\n        } else {\n            balance--;\n        }\n        if (balance < 0) {\n            return false;\n        }\n    }\n    return (balance === 0);\n}\nfunction build(s: string): void {\n    if (s.length == (2 * n)) {\n        candidates.push(s);\n        return;\n    }\n    build((s + \"(\"));\n    build((s + \")\"));\n}\nbuild(\"\");\nreturn candidates.filter((s) => isValid(s));","lineMap":{"2":1,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":10,"11":11,"12":14,"14":17,"15":18,"16":19,"17":21,"18":22,"19":24,"20":25},"statementBundles":{"2":{"startLine":1,"endLine":2},"9":{"startLine":8,"endLine":9},"11":{"startLine":11,"endLine":13},"12":{"startLine":14,"endLine":16},"16":{"startLine":19,"endLine":20},"18":{"startLine":22,"endLine":23}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static boolean isValid(String s) {\n    int balance = 0;\n    for (char ch : s.toCharArray()) {\n        if (ch == '(') {\n            balance++;\n        } else {\n            balance--;\n        }\n        if (balance < 0) {\n            return false;\n        }\n    }\n    return balance == 0;\n}\n\nprivate static void build(String s, int n, List<String> candidates) {\n    if (s.length() == (2 * n)) {\n        candidates.add(s);\n        return;\n    }\n    build((s + \"(\"), n, candidates);\n    build((s + \")\"), n, candidates);\n}\n\nList<String> candidates = new ArrayList<>();\nbuild(\"\", n, candidates);\nreturn candidates.stream().filter(s -> isValid(s)).collect(java.util.stream.Collectors.toList());","lineMap":{"2":25,"4":2,"5":3,"6":4,"7":5,"8":6,"9":7,"10":9,"11":10,"12":13,"14":17,"15":18,"16":19,"17":21,"18":22,"19":26,"20":27},"statementBundles":{"9":{"startLine":7,"endLine":8},"11":{"startLine":10,"endLine":12},"12":{"startLine":13,"endLine":16},"16":{"startLine":19,"endLine":20},"18":{"startLine":22,"endLine":23}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<string> candidates = new();\nbool IsValid(List<string> s) {\n    int balance = 0;\n    foreach (string ch in s) {\n        if (ch == \"(\") {\n            balance++;\n        } else {\n            balance--;\n        }\n        if (balance < 0) {\n            return false;\n        }\n    }\n    return balance == 0;\n    return false;\n}\nvoid Build(string s) {\n    if (s.Length == 2 * n) {\n        candidates.Add(s);\n        return;\n    }\n    Build(s + \"(\");\n    Build(s + \")\");\n}\nBuild(\"\");\nreturn candidates.Where(s => IsValid(s.Select(ch => ch.ToString()).ToList())).Select(s => s).ToList();","lineMap":{"2":1,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":10,"11":11,"12":14,"14":18,"15":19,"16":20,"17":22,"18":23,"19":25,"20":26},"statementBundles":{"2":{"startLine":1,"endLine":2},"9":{"startLine":8,"endLine":9},"11":{"startLine":11,"endLine":13},"12":{"startLine":14,"endLine":17},"16":{"startLine":20,"endLine":21},"18":{"startLine":23,"endLine":24}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<void(string)> build;\n\nvector<string> candidates;\nauto is_valid = [&]( string s ) -> bool {\n    int balance = 0;\n    for (char ch : s) {\n        if (ch == '(') {\n            balance++;\n        } else {\n            balance--;\n        }\n        if (balance < 0) {\n            return false;\n        }\n    }\n    return (balance == 0);\n};\nbuild = [&]( string s ) -> void {\n    if (s.size() == (2 * n)) {\n        candidates.push_back(s);\n        return;\n    }\n    build((s + \"(\"));\n    build((s + \")\"));\n};\nbuild(\"\");\nvector<string> result;\nfor (string s : candidates) {\n    if (is_valid(s)) {\n        result.push_back(s);\n    }\n}\nreturn result;","lineMap":{"2":3,"4":5,"5":6,"6":7,"7":8,"8":9,"9":10,"10":12,"11":13,"12":16,"14":19,"15":20,"16":21,"17":23,"18":24,"19":26,"20":27},"statementBundles":{"2":{"startLine":3,"endLine":4},"9":{"startLine":10,"endLine":11},"11":{"startLine":13,"endLine":15},"12":{"startLine":16,"endLine":18},"16":{"startLine":21,"endLine":22},"18":{"startLine":24,"endLine":25},"20":{"startLine":27,"endLine":33}}}}}},{"id":"waste-probe","kind":"case-probe","chapter":"The problem","eyebrow":"Name the waste","title":"How early could the string )((( have been abandoned?","workspacePanel":"trace","summary":"One of the 16 candidates built in full.","options":[{"id":"doomed-early","label":"At the first character: a leading ) can never be matched","rationale":"A leading ) has no opener to answer it, so every string starting with one is invalid no matter what follows. Building the remaining three characters is pure waste the brute force still does.","isCorrect":true},{"id":"length","label":"Not until its length was checked","rationale":"The length is fine; the string is doomed by structure, a closer before any opener, not by size."},{"id":"nothing","label":"Not at all; you must finish a string to judge it","rationale":"You can judge a prefix: once a closer outnumbers the openers before it, no ending can rescue it."}],"answer":"At character one. A closer with no opener waiting can never balance, so the moment ) leads, the whole branch is doomed, yet the brute force builds it out anyway."},{"id":"add-open","kind":"case-probe","chapter":"The idea","eyebrow":"Find the first rule","title":"Building left to right, when is it safe to add an opener?","workspacePanel":"visualizer","summary":"You are partway through building one arrangement of brackets.","options":[{"id":"opens-left","label":"Whenever you have not yet placed all n openers","rationale":"A valid string uses exactly n openers, so you can add one any time fewer than n have been used; spending the last one is always fine on its own.","isCorrect":true},{"id":"always","label":"Always, openers are harmless","rationale":"Adding an (n+1)th opener guarantees more than n pairs, so the count of openers has to be capped at n."},{"id":"balanced","label":"Only when openers and closers are equal","rationale":"That would forbid (( entirely; nesting is allowed, so openers may run ahead of closers."}],"answer":"Whenever fewer than n openers have been placed. You have exactly n to spend, so an opener is safe until they run out.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"open-state","state":{"stack":["("],"stackActive":[0],"labels":{"stack":"path"},"open_count":1,"close_count":0}}]}},{"id":"add-close","kind":"case-probe","chapter":"The idea","eyebrow":"Find the key rule","title":"And when is it safe to add a closer?","workspacePanel":"visualizer","summary":"path = ((, open_count = 2, close_count = 0.","options":[{"id":"close-lt-open","label":"Only while closers placed so far are fewer than openers placed","rationale":"Each closer must match an earlier unmatched opener; if closers ever caught up to openers, the next closer would have nothing to match, so the gate is closers < openers.","isCorrect":true},{"id":"close-lt-n","label":"Whenever fewer than n closers have been placed","rationale":"That ignores ordering: with one opener down you could still add two closers, producing ()) which is invalid. The cap must be the openers placed, not n."},{"id":"anytime","label":"Anytime there are closers left to place","rationale":"A closer placed before its opener, like a leading ), can never match; availability is not the constraint, an unmatched opener is."}],"answer":"Only while fewer closers than openers have been placed. Every closer must answer an opener that is still waiting, so closers can never catch up to openers mid-string.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"close-state","state":{"stack":["(","("],"stackActive":[1],"labels":{"stack":"path"},"open_count":2,"close_count":0}}]}},{"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":{"stack":["("],"stackActive":[0],"labels":{"stack":"path"},"open_count":1,"close_count":0}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it move","title":"Grow valid prefixes, back up at dead ends","workspacePanel":"visualizer","body":["Build the string one bracket at a time. At each step the two gates decide what is allowed: an opener while open_count < n, a closer while close_count < open_count. When the string reaches 2n characters it is one finished answer.","Watch the two arrangements for n = 2 fall out without a single invalid string ever being built."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"stack":[],"labels":{"stack":"path"},"open_count":0,"close_count":0}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Build the arrangements","title":"Generate every balanced string for n = 2","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"first-open","state":{"stack":["("],"stackActive":[0],"labels":{"stack":"path"},"open_count":1,"close_count":0}},{"id":"second-open","state":{"stack":["(","("],"stackActive":[1],"labels":{"stack":"path"},"open_count":2,"close_count":0}},{"id":"first-close","state":{"stack":["(","(",")"],"stackActive":[2],"labels":{"stack":"path"},"open_count":2,"close_count":1}},{"id":"record-nested","state":{"stack":["(","(",")",")"],"stackActive":[3],"labels":{"stack":"path"},"open_count":2,"close_count":2}},{"id":"other-branch","state":{"stack":["(",")"],"stackActive":[1],"labels":{"stack":"path"},"open_count":1,"close_count":1}},{"id":"record-flat","state":{"stack":["(",")","(",")"],"stackActive":[3],"labels":{"stack":"path"},"open_count":2,"close_count":2}}]},"beats":[{"id":"first-open","title":"With an empty string, which bracket can go first?","summary":"open_count = 0, close_count = 0, n = 2.","options":[{"id":"open","label":"An opener: close_count < open_count fails, so a closer is not allowed","rationale":"With open_count = 0, the closer gate close_count < open_count is 0 < 0, which is false, so the only legal first character is an opener.","isCorrect":true},{"id":"close","label":"A closer","rationale":"A leading closer has no opener to match; the gate close_count < open_count blocks it at the start."},{"id":"either","label":"Either one","rationale":"Only the opener gate is open at the start; a closer is forbidden until an opener is waiting."}],"answer":"An opener. The closer gate (close_count < open_count) is shut while open_count is 0, so the string must start with (."},{"id":"second-open","title":"Now ( is placed: open_count = 1. Add a second opener?","summary":"open_count = 1, close_count = 0, n = 2.","options":[{"id":"yes","label":"Yes: open_count = 1 is still under n = 2, so (( is allowed","rationale":"The opener gate open_count < n is 1 < 2, true, so a second opener is legal, nesting the pair.","isCorrect":true},{"id":"no","label":"No, two openers in a row is invalid","rationale":"Nesting is fine; (()) is a valid arrangement, so (( is a legal prefix."},{"id":"must-close","label":"No, you must close first","rationale":"You may close here, but you are not forced to; the opener gate is still open at 1 < 2."}],"answer":"Yes. open_count = 1 is under n, so a second opener is allowed, building toward the nested (())."},{"id":"first-close","title":"At ((, open_count = 2 = n. What is allowed now?","summary":"open_count = 2, close_count = 0, n = 2.","options":[{"id":"close-only","label":"Only a closer: openers are spent, and close_count < open_count lets one in","rationale":"open_count = 2 is not under n, so no more openers; meanwhile close_count < open_count is 0 < 2, so a closer is allowed, giving (().","isCorrect":true},{"id":"open","label":"Another opener","rationale":"All n openers are placed (open_count = 2 = n), so the opener gate is shut."},{"id":"neither","label":"Nothing, this is a dead end","rationale":"It is not dead: a closer is legal here and leads to the finished (())."}],"answer":"Only a closer. The openers are used up, but close_count < open_count is open, so ) is added to make (()."},{"id":"record-nested","title":"Another closer gives (()), length 4 = 2n. What happens?","summary":"The path has reached length 4 = 2n.","options":[{"id":"record","label":"Record (()) and back up to try other choices","rationale":"At length 2n the string is complete and balanced, so it is saved; the search then unwinds to explore the choices it skipped.","isCorrect":true},{"id":"extend","label":"Keep adding brackets","rationale":"The string is already 2n long; adding more would exceed n pairs. It is recorded and the search backtracks."},{"id":"stop","label":"Stop entirely, one answer is enough","rationale":"There are more arrangements to find; the search backtracks rather than stopping."}],"answer":"Record (()) and backtrack. Length 2n means complete, so it is saved and the search returns to the last open choice."},{"id":"other-branch","title":"Unwinding to the single ( , the other choice was a closer: (). Then?","summary":"open_count = 1, close_count = 1.","options":[{"id":"open-again","label":"An opener is allowed again: open_count = 1 < n, building ()(","rationale":"Back at (), open_count = 1 is under n so an opener is legal, and close_count < open_count is shut at 1 < 1, so the next character is (, heading toward ()().","isCorrect":true},{"id":"close","label":"Another closer","rationale":"close_count < open_count is 1 < 1, false, so a closer is blocked here; only an opener fits."},{"id":"done","label":"Nothing, () is already an answer","rationale":"() has length 2 while 2n = 4. It remains a prefix, and an opener extends it."}],"answer":"An opener, giving ()(. With open_count under n and the closer gate shut, ( is the only legal next character."},{"id":"record-flat","title":"A final closer makes ()(), length 4. The result set?","summary":"The second full-length path just arrived.","options":[{"id":"both","label":"(()) and ()(), the two valid arrangements, with no invalid string ever built","rationale":"The two gates pruned every dead branch before it grew, so the search produced exactly the two answers and nothing else.","isCorrect":true},{"id":"flat-only","label":"Just ()()","rationale":"(()) was recorded earlier on the nested branch; both arrangements are in the result."},{"id":"more","label":"Four or more strings","rationale":"For n = 2 there are exactly two balanced arrangements; the gates produce those two and no extras."}],"answer":"(()) and ()(). The gates kept every prefix valid, so the search built exactly the two answers and skipped all 14 dead strings."}]},{"id":"close-guard-pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","workspacePanel":"trace","title":"Could the path be left as-is after recursion returns?","summary":"The gates are right, and one shared path list grows and shrinks as the search moves. Dropping the path.pop() after recursion looks harmless, since the next choice will just append over it. Watch what the sibling branch inherits.","pitfall":"The code below appends each choice and recurses but never pops it, so the shared path keeps every character from the branch it just finished.","whyItMatters":"Without the pop, a finished branch leaves its characters behind. When the search backs up to try the sibling choice, it appends onto the stale (()) instead of the ( it should return to, and builds garbage like (())). Restore the path with path.pop() after every recursive call so each sibling starts from the state its parent left.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def generateParenthesis(n: int) -> list[str]:\n    result: list[str] = []\n    choices: list[str] = [\"(\", \")\"]\n    path: list[str] = []\n    def backtrack(path: list[str], open_count: int, close_count: int) -> None:\n        if len(path) == 2 * n:\n            result.append(\"\".join(path))\n            return\n        for choice in choices:\n            if choice == \"(\" and open_count >= n:\n                continue\n            if choice == \")\" and close_count >= open_count:\n                continue\n            path.append(choice)\n            if choice == \"(\":\n                backtrack(path, open_count + 1, close_count)\n            else:\n                backtrack(path, open_count, close_count + 1)\n    backtrack(path, 0, 0)\n    return result","steps":[{"id":"build-nested","title":"n = 2: the first branch grows ( ( ) ) and records (())","codeLine":7,"summary":"Appending ( then ( then ) then ) reaches length 4, so (()) is recorded. So far so good.","state":{"stack":["(","(",")",")"],"stackActive":[3],"labels":{"stack":"path"},"open_count":2,"close_count":2}},{"id":"no-pop","title":"The branch returns, but path.pop() never runs","codeLine":18,"summary":"The recursive calls unwind back toward the single (, yet every character stays in the shared path.","state":{"stack":["(","(",")",")"],"stackActive":[3],"labels":{"stack":"path"},"open_count":1,"close_count":0}},{"id":"leak","title":"The sibling choice appends onto the stale path","codeLine":14,"summary":"Back at open_count = 1, the next choice ) appends to (()) instead of (, giving (())), which no valid arrangement could produce.","state":{"stack":["(","(",")",")",")"],"stackActive":[4],"labels":{"stack":"path"},"open_count":1,"close_count":1}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const result = [];\nconst choices = [\"(\", \")\"];\nconst path = [];\nfunction backtrack(path, openCount, closeCount) {\n    if (path.length == (2 * n)) {\n        result.push(path.join(\"\"));\n        return;\n    }\n    for (const choice of choices) {\n        if (choice === \"(\" && openCount >= n) {\n            continue;\n        }\n        if (choice === \")\" && closeCount >= openCount) {\n            continue;\n        }\n        path.push(choice);\n        if (choice === \"(\") {\n            backtrack(path, (openCount + 1), closeCount);\n        } else {\n            backtrack(path, openCount, (closeCount + 1));\n        }\n    }\n}\nbacktrack(path, 0, 0);\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"6":5,"7":6,"8":7,"9":9,"10":10,"11":11,"12":13,"13":14,"14":16,"15":17,"16":18,"17":19,"18":20,"19":24,"20":25},"statementBundles":{"4":{"startLine":3,"endLine":4},"8":{"startLine":7,"endLine":8},"11":{"startLine":11,"endLine":12},"13":{"startLine":14,"endLine":15},"18":{"startLine":20,"endLine":23}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const result: Array<string> = [];\nconst choices = [\"(\", \")\"];\nconst path: Array<string> = [];\nfunction backtrack(path: Array<string>, openCount: number, closeCount: number): void {\n    if (path.length == (2 * n)) {\n        result.push(path.join(\"\"));\n        return;\n    }\n    for (const choice of choices) {\n        if (choice === \"(\" && openCount >= n) {\n            continue;\n        }\n        if (choice === \")\" && closeCount >= openCount) {\n            continue;\n        }\n        path.push(choice);\n        if (choice === \"(\") {\n            backtrack(path, (openCount + 1), closeCount);\n        } else {\n            backtrack(path, openCount, (closeCount + 1));\n        }\n    }\n}\nbacktrack(path, 0, 0);\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"6":5,"7":6,"8":7,"9":9,"10":10,"11":11,"12":13,"13":14,"14":16,"15":17,"16":18,"17":19,"18":20,"19":24,"20":25},"statementBundles":{"4":{"startLine":3,"endLine":4},"8":{"startLine":7,"endLine":8},"11":{"startLine":11,"endLine":12},"13":{"startLine":14,"endLine":15},"18":{"startLine":20,"endLine":23}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<string> result = new();\nList<string> choices = new() { \"(\", \")\" };\nList<string> path = new();\nvoid Backtrack(List<string> path, int openCount, int closeCount) {\n    if (path.Count == 2 * n) {\n        result.Add(string.Join(\"\", path));\n        return;\n    }\n    foreach (string choice in choices) {\n        if (choice == \"(\" && openCount >= n) {\n            continue;\n        }\n        if (choice == \")\" && closeCount >= openCount) {\n            continue;\n        }\n        path.Add(choice);\n        if (choice == \"(\") {\n            Backtrack(path, openCount + 1, closeCount);\n        } else {\n            Backtrack(path, openCount, closeCount + 1);\n        }\n    }\n}\nBacktrack(path, 0, 0);\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"6":5,"7":6,"8":7,"9":9,"10":10,"11":11,"12":13,"13":14,"14":16,"15":17,"16":18,"17":19,"18":20,"19":24,"20":25},"statementBundles":{"4":{"startLine":3,"endLine":4},"8":{"startLine":7,"endLine":8},"11":{"startLine":11,"endLine":12},"13":{"startLine":14,"endLine":15},"18":{"startLine":20,"endLine":23}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<void(vector<string>&, int, int)> backtrack;\n\nvector<string> result;\nvector<string> choices{\"(\", \")\"};\nvector<string> path;\nbacktrack = [&]( vector<string>& path, int open_count, int close_count ) -> void {\n    if (path.size() == (2 * n)) {\n        result.push_back(joinValues(path, \"\"));\n        return;\n    }\n    for (string choice : choices) {\n        if ((choice == string(\"(\") && open_count >= n)) {\n            continue;\n        }\n        if (((choice == string(\")\")) && close_count >= open_count)) {\n            continue;\n        }\n        path.push_back(choice);\n        if (choice == string(\"(\")) {\n            backtrack(path, (open_count + 1), close_count);\n        } else {\n            backtrack(path, open_count, (close_count + 1));\n        }\n    }\n};\nbacktrack(path, 0, 0);\nreturn result;","lineMap":{"2":3,"3":4,"4":5,"6":7,"7":8,"8":9,"9":11,"10":12,"11":13,"12":15,"13":16,"14":18,"15":19,"16":20,"17":21,"18":22,"19":26,"20":27},"statementBundles":{"4":{"startLine":5,"endLine":6},"8":{"startLine":9,"endLine":10},"11":{"startLine":13,"endLine":14},"13":{"startLine":16,"endLine":17},"18":{"startLine":22,"endLine":25}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static void backtrack(List<String> path, int openCount, int closeCount, int n, List<String> result, List<String> choices) {\n    if (path.size() == (2 * n)) {\n        result.add(String.join(\"\", path));\n        return;\n    }\n    for (String choice : choices) {\n        if ((\"(\".equals(choice) && openCount >= n)) {\n            continue;\n        }\n        if ((\")\".equals(choice) && closeCount >= openCount)) {\n            continue;\n        }\n        path.add(choice);\n        if (\"(\".equals(choice)) {\n            backtrack(path, (openCount + 1), closeCount, n, result, choices);\n        } else {\n            backtrack(path, openCount, (closeCount + 1), n, result, choices);\n        }\n    }\n}\n\nList<String> result = new ArrayList<>();\nList<String> choices = new ArrayList<>(List.of(\"(\", \")\"));\nList<String> path = new ArrayList<>();\nbacktrack(path, 0, 0, n, result, choices);\nreturn result;","lineMap":{"2":22,"3":23,"4":24,"6":2,"7":3,"8":4,"9":6,"10":7,"11":8,"12":10,"13":11,"14":13,"15":14,"16":15,"17":16,"18":17,"19":25,"20":26},"statementBundles":{"8":{"startLine":4,"endLine":5},"11":{"startLine":8,"endLine":9},"13":{"startLine":11,"endLine":12},"18":{"startLine":17,"endLine":20}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["The two gates produced exactly the right arrangements for n = 2. The inputs that test them are the smallest counts, where there is barely a choice to make.","Two are worth a look: n = 1, the smallest input allowed, and the very first character of any search, where one gate is already shut."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"stack":[],"labels":{"stack":"path"},"open_count":0,"close_count":0}}]}},{"id":"n-one-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"For n = 1, what does the search produce?","workspacePanel":"visualizer","summary":"The search starts with open_count = 0, close_count = 0, n = 1.","options":[{"id":"one","label":"() only","rationale":"The opener goes first (the closer gate is shut at the start), then a closer matches it, giving the single arrangement (); no other ordering passes the gates.","isCorrect":true},{"id":"two","label":"() and )(","rationale":")( is exactly what the close_count < open_count gate forbids; only () is well-formed for one pair."},{"id":"empty","label":"An empty result","rationale":"() is a valid arrangement, so the result holds one string, not none."}],"answer":"() only. The opener must lead and the closer matches it, so a single pair has exactly one balanced arrangement.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"n-one-state","state":{"stack":[],"labels":{"stack":"path"},"open_count":0,"close_count":0}}]}},{"id":"first-char-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"From the empty start, can the search ever place ) first?","workspacePanel":"visualizer","summary":"open_count = 0, close_count = 0, no character placed yet.","options":[{"id":"never","label":"Never: the closer gate is shut while open_count is 0","rationale":"The gate close_count < open_count reads 0 < 0, which is false, so a closer can never be the first character; every search begins with an opener.","isCorrect":true},{"id":"sometimes","label":"Yes, when there are closers left to place","rationale":"Having closers left is not the constraint; the gate is close_count < open_count, and with open at 0 no closer can pass, however many remain."},{"id":"depends-n","label":"Yes, once n is large enough","rationale":"n bounds how many openers can appear. At the start the closer gate is 0 < 0, so a leading ) is always refused."}],"answer":"Never. At the empty start close_count < open_count is 0 < 0, false, so the search refuses a leading ) for any n and always begins with an opener.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"first-char-state","state":{"stack":[],"labels":{"stack":"path"},"open_count":0,"close_count":0}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Turn the rule into code","workspacePanel":"visualizer","summary":"Two gates keep every prefix valid.","body":["Grow the string one bracket at a time, letting an opener through while opens remain and a closer through only while it would answer an opener already placed.","When the string reaches full length it is one finished arrangement; record it and let the search back up to explore the choices it passed over."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"stack":["("],"stackActive":[0],"labels":{"stack":"path"},"open_count":1,"close_count":0}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the guarded backtracking","eyebrow":"Code the rule","summary":"Now turn the two gates into code: start a result list, record the path once it reaches 2n, then loop over the two brackets, skip an opener past n opens or a closer that has no waiting opener, and for each one that passes append it, recurse with the updated count, and pop it back off. Kick the search off from the empty path, then return the collected strings.","workspacePanel":"code","checkpoints":[{"id":"init-result","title":"Initialize result","description":"Create the list that will collect complete strings.","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 an accumulator for all complete parentheses strings.","doneWhen":"This step is done when the function creates an empty result list before recursion begins.","shouldFailWhen":"This step should fail if complete strings have nowhere persistent to be stored.","roles":["result accumulator","complete strings"],"mustProve":["The result accumulator is initialized before the helper runs."],"mustNotAccept":["Returning only the current path."],"equivalentVariants":["Use any list-like accumulator for completed strings."],"proofSnippets":[{"id":"py-generate-parentheses-init-result","language":"python","code":"class Solution:\n    def generateParenthesis(self, n: int) -> list[str]:\n        result = []\n        return result"}]},"commonMistakes":["Forgetting to collect all complete strings","Using a single string as the only result"],"hint":"The recursive helper should append complete strings into one shared list."},{"id":"base-case","title":"Emit complete path","description":"When the path reaches length 2n, append the completed string and return.","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":"Recognize a complete parentheses string and emit it as a snapshot.","doneWhen":"This step is done when the helper joins or copies the path into result once its length is 2n and returns from that branch.","shouldFailWhen":"This step should fail if complete paths keep recursing or append a mutable path object directly.","roles":["completion condition","path snapshot","terminal return"],"mustProve":["The helper checks for a complete path.","A completed path is emitted and the branch returns."],"mustNotAccept":["Continuing to add parentheses after length 2n."],"equivalentVariants":["Join the path list into a string before appending.","Carry the path as a string and append that string at completion."],"proofSnippets":[{"id":"py-generate-parentheses-base-case","language":"python","code":"class Solution:\n    def generateParenthesis(self, n: int) -> list[str]:\n        result = []\n        def backtrack(path: list[str], open_count: int, close_count: int) -> None:\n            if len(path) == 2 * n:\n                result.append(\"\".join(path))\n                return\n            backtrack(path, open_count, close_count)\n        return result"}]},"commonMistakes":["Appending the mutable path list instead of a string snapshot","Forgetting to return after emitting"],"hint":"A complete string has exactly 2n characters."},{"id":"choice-loop","title":"Loop over choices","description":"Try the two parenthesis choices from each recursive state.","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":"Enumerate possible next characters for the current path.","doneWhen":"This step is done when the helper loops over the open and close parenthesis choices.","shouldFailWhen":"This step should fail if the code only tries one fixed next character.","roles":["choice loop","open choice","close choice"],"mustProve":["The helper iterates over a parenthesis choice space."],"mustNotAccept":["Checking only one candidate character."],"equivalentVariants":["Loop over a two-item choices list.","Use any equivalent choice iteration that considers both parenthesis types."],"proofSnippets":[{"id":"py-generate-parentheses-choice-loop","language":"python","code":"class Solution:\n    def generateParenthesis(self, n: int) -> list[str]:\n        result = []\n        choices = [\"(\", \")\"]\n        def backtrack(path: list[str], open_count: int, close_count: int) -> None:\n            if len(path) == 2 * n:\n                result.append(\"\".join(path))\n                return\n            for choice in choices:\n                backtrack(path, open_count, close_count)\n        return result"}]},"commonMistakes":["Trying only open parentheses first without ever considering close choices","Generating fixed strings instead of branching"],"hint":"Every state can consider `(` and `)`, then guards decide which are legal."},{"id":"candidate-guard","title":"Skip invalid choices","description":"Skip opens after n opens and skip closes that would exceed opens.","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":"Reject any next parenthesis that cannot lead to a valid final string before mutating the path.","doneWhen":"This step is done when the code skips `(` after n opens and skips `)` whenever closes would catch or exceed opens.","shouldFailWhen":"This step should fail if invalid closing parentheses can be appended.","roles":["open count","close count","candidate guard"],"mustProve":["Open choices are bounded by n.","Close choices are bounded by the current open count."],"mustNotAccept":["Allowing more closes than opens.","Allowing more than n opens."],"equivalentVariants":["Use `continue` guards before append.","Use equivalent conditionals that only allow valid choices to reach append."],"proofSnippets":[{"id":"py-generate-parentheses-candidate-guard","language":"python","code":"class Solution:\n    def generateParenthesis(self, n: int) -> list[str]:\n        result = []\n        choices = [\"(\", \")\"]\n        def backtrack(path: list[str], open_count: int, close_count: int) -> None:\n            if len(path) == 2 * n:\n                result.append(\"\".join(path))\n                return\n            for choice in choices:\n                if choice == \"(\" and open_count >= n:\n                    continue\n                if choice == \")\" and close_count >= open_count:\n                    continue\n                backtrack(path, open_count, close_count)\n        return result"}]},"commonMistakes":["Adding a close parenthesis when closes already equal opens","Adding more than n open parentheses"],"hint":"Invalid candidates should be filtered before they touch the path."},{"id":"choose-explore-unchoose","title":"Choose, recurse, unchoose","description":"Append the chosen parenthesis, recurse with updated counts, 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 the path for one choice, recursively explore the branch, then restore the path for the next choice.","doneWhen":"This step is done when each valid choice appends to the path, recurses with the corresponding updated count, and pops the path afterward.","shouldFailWhen":"This step should fail if the code appends without cleanup or recurses without changing counts.","roles":["path mutation","recursive call","rollback cleanup"],"mustProve":["The chosen parenthesis is appended before recursion.","The recursive call advances the matching count.","The append is undone after recursion."],"mustNotAccept":["Missing path cleanup.","Recursing with unchanged open and close counts."],"equivalentVariants":["Use append/pop around recursion.","Use equivalent mutable path operations as long as each branch is restored."],"proofSnippets":[{"id":"py-generate-parentheses-choose-explore-unchoose","language":"python","code":"class Solution:\n    def generateParenthesis(self, n: int) -> list[str]:\n        result = []\n        choices = [\"(\", \")\"]\n        def backtrack(path: list[str], open_count: int, close_count: int) -> None:\n            if len(path) == 2 * n:\n                result.append(\"\".join(path))\n                return\n            for choice in choices:\n                if choice == \"(\" and open_count >= n:\n                    continue\n                if choice == \")\" and close_count >= open_count:\n                    continue\n                path.append(choice)\n                if choice == \"(\":\n                    backtrack(path, open_count + 1, close_count)\n                else:\n                    backtrack(path, open_count, close_count + 1)\n                path.pop()\n        return result"}]},"commonMistakes":["Forgetting to pop the choice","Incrementing the wrong count"],"hint":"After recursion returns, restore the path exactly as it was before the choice."},{"id":"initial-call","title":"Start recursion","description":"Start with an empty path and zero open and close parentheses.","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":"Kick off the recursive search from the empty partial string.","doneWhen":"This step is done when the function calls the helper with an empty path, zero opens, and zero closes.","shouldFailWhen":"This step should fail if the helper is never called or starts from a non-empty invalid path.","roles":["initial helper call","empty path","zero counts"],"mustProve":["The recursive helper is invoked after it is defined."],"mustNotAccept":["Returning before calling the helper."],"equivalentVariants":["Start with an empty list path.","Start with an empty string path if the rest of the implementation is immutable."],"proofSnippets":[{"id":"py-generate-parentheses-initial-call","language":"python","code":"class Solution:\n    def generateParenthesis(self, n: int) -> list[str]:\n        result = []\n        choices = [\"(\", \")\"]\n        def backtrack(path: list[str], open_count: int, close_count: int) -> None:\n            if len(path) == 2 * n:\n                result.append(\"\".join(path))\n                return\n            for choice in choices:\n                if choice == \"(\" and open_count >= n:\n                    continue\n                if choice == \")\" and close_count >= open_count:\n                    continue\n                path.append(choice)\n                if choice == \"(\":\n                    backtrack(path, open_count + 1, close_count)\n                else:\n                    backtrack(path, open_count, close_count + 1)\n                path.pop()\n        backtrack([], 0, 0)"}]},"commonMistakes":["Never invoking the helper","Starting with one parenthesis already in the path"],"hint":"The root of the search tree is the empty path."},{"id":"return-result","title":"Return all strings","description":"Return the accumulator after recursive search finishes.","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 complete list of generated well-formed strings.","doneWhen":"This step is done when the function returns the result accumulator after the initial recursive call.","shouldFailWhen":"This step should fail if the function returns the current path or only the number of strings.","roles":["result accumulator","final return"],"mustProve":["The returned value is the accumulator populated by recursion."],"mustNotAccept":["Returning a count instead of the generated strings."],"equivalentVariants":["Return the shared result list after search completes."],"proofSnippets":[{"id":"py-generate-parentheses-return-result","language":"python","code":"class Solution:\n    def generateParenthesis(self, n: int) -> list[str]:\n        result = []\n        choices = [\"(\", \")\"]\n        def backtrack(path: list[str], open_count: int, close_count: int) -> None:\n            if len(path) == 2 * n:\n                result.append(\"\".join(path))\n                return\n            for choice in choices:\n                if choice == \"(\" and open_count >= n:\n                    continue\n                if choice == \")\" and close_count >= open_count:\n                    continue\n                path.append(choice)\n                if choice == \"(\":\n                    backtrack(path, open_count + 1, close_count)\n                else:\n                    backtrack(path, open_count, close_count + 1)\n                path.pop()\n        backtrack([], 0, 0)\n        return result"}]},"commonMistakes":["Returning the path stack","Returning before recursion fills the result"],"hint":"The result list is the output."}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Generate only valid prefixes: an opener while opens remain, a closer only while it matches a waiting opener, so no invalid string is ever built.","workspacePanel":"code","body":["The leap from build-then-filter to guarded backtracking is pruning the branch the moment it can no longer lead anywhere, instead of finishing a doomed string to reject it.","The two gates encode well-formedness directly: capping openers at n, and keeping closers from ever passing the openers placed."],"takeaways":[{"title":"Prune invalid prefixes early","body":"A closer with no opener waiting dooms the whole branch; refusing it early skips every dead string underneath."},{"title":"Gate the closer on open, not n","body":"A closer must answer an opener still waiting, so its cap is the openers placed so far, never the total pair count."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
