{"id":"valid-parentheses","title":"Valid Parentheses","difficulty":"easy","patterns":["monotonic-stack"],"primaryConcept":"stack-lifo-validation","concepts":["stack-lifo-validation"],"problemForm":"intro","companies":[],"category":"stacks-queues","compareMode":"exact","description":"Given a string `s` containing only the characters `(`, `)`, `{`, `}`, `[` and `]`, return `true` if the brackets are valid.\n\nA string is valid when:\n- Every opening bracket is closed by the same type of bracket.\n- Brackets close in the correct order.\n- Every closing bracket has a matching opening bracket before it.","examples":[{"input":"s = \"()\"","output":"true","explanation":"The single opening parenthesis is closed by the matching parenthesis."},{"input":"s = \"()[]{}\"","output":"true","explanation":"Each bracket pair is complete and closes in order."},{"input":"s = \"(]\"","output":"false","explanation":"The closing bracket `]` does not match the most recent opening bracket `(`."},{"input":"s = \"([)]\"","output":"false","explanation":"The brackets are paired by type but close in the wrong order."}],"constraints":[{"id":"1-len-s-10-4","text":"1 <= len(s) <= 10^4","check":{"kind":"sizeRange","target":"s","measure":"stringLength","min":1,"max":10000}},{"id":"s-contains-only-parentheses-square-brackets-and-curly-braces","text":"s contains only parentheses, square brackets, and curly braces."}],"starterCode":"class Solution:\n    def isValid(self, s: str) -> bool:\n        # Your code here\n        pass","functionName":"isValid","testCases":[{"id":"1","input":{"s":"()"},"expected":true,"description":"Single matching pair."},{"id":"2","input":{"s":"()[]{}"},"expected":true,"description":"Multiple adjacent valid pairs."},{"id":"3","input":{"s":"(]"},"expected":false,"description":"Wrong bracket type."},{"id":"4","input":{"s":"([)]"},"expected":false,"description":"Wrong closing order."},{"id":"5","input":{"s":"((("},"expected":false,"description":"Unclosed opening brackets remain."},{"id":"6","input":{"s":"]"},"expected":false,"description":"Closing bracket with no opener."},{"id":"h1","input":{"s":"{}[]"},"description":"Two valid pairs in sequence.","expected":true},{"id":"h2","input":{"s":"({[]})"},"description":"Nested brackets close in the correct order.","expected":true},{"id":"h3","input":{"s":"[(])"},"description":"Crossed closing order is invalid.","expected":false},{"id":"h4","input":{"s":"(()))"},"description":"An extra closing bracket breaks balance.","expected":false}],"hints":[{"level":1,"content":"When you see a closing bracket, it must match the most recent unmatched opening bracket.","revealPattern":false},{"level":2,"content":"Use a stack to remember opening brackets in the order they need to be closed.","revealPattern":true},{"level":3,"content":"Push openers. For a closer, the stack must be non-empty and its top must be the matching opener. At the end, the stack must be empty.","revealPattern":true}],"guidedFlow":{"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach that preserves nesting order as the string is scanned.","approaches":[{"id":"stack-with-pairs","name":"Stack of openings","summary":"Push opening brackets, then pop and compare whenever a closing bracket appears.","decisionReason":"It stores only unmatched openings and checks the exact nesting order.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Uses stack space for nesting depth, but validates each character once."],"isOptimal":true,"steps":["Push openings.","On a close, require a nonempty stack.","Pop and compare the expected pair.","Finish with an empty stack."]},{"id":"count-brackets","name":"Count bracket types","summary":"Track counts of each bracket type.","decisionReason":"Counts can balance totals but cannot detect incorrect nesting order.","complexity":{"time":"O(n)","space":"O(1)"},"tradeoffs":["Small state, but accepts invalid strings such as \"([)]\"."],"isOptimal":false}]},"codingCheckpoints":[{"id":"init-stack","title":"Initialize the opener stack","description":"Create an empty stack to hold unmatched opening brackets.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"initializes_empty_stack","scope":"init-stack","readMode":"stack-value-query-v1"}]},"commonMistakes":["Using only a counter","Replacing the stack with a single variable"],"hint":"You need LIFO order, so start with an empty stack.","semanticSpec":{"intent":"Initialize a LIFO stack before scanning the string.","doneWhen":"This step is done when an empty LIFO state exists before delimiter processing begins.","shouldFailWhen":"This step should fail if the code uses only counters or stores only the most recent opener in a scalar.","roles":["stack","unmatched openers"],"mustProve":["A LIFO stack is initialized before scanning."],"mustNotAccept":["Using a plain count per bracket type.","Overwriting one scalar instead of preserving nesting."],"equivalentVariants":["Use `stack = []`.","Use an equivalent empty LIFO collection."],"proofSnippets":[{"id":"py-valid-parentheses-init-stack","language":"python","code":"def isValid(s: str) -> bool:\n    stack = []\n    return True"}]}},{"id":"push-openers","title":"Push opening brackets","description":"When the current character is an opening bracket, push that opener onto the unmatched-opener stack.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"pushes_unmatched_opening_delimiter","scope":"push-current","readMode":"stack-value-query-v1"}]},"commonMistakes":["Pushing closing brackets too","Replacing the stack with a single variable"],"hint":"Every unmatched opener waits on the stack.","semanticSpec":{"intent":"Store unmatched opening brackets in LIFO order as they are encountered.","doneWhen":"This step is done when the scan pushes opening bracket characters onto the stack for later closer checks.","shouldFailWhen":"This step should fail if the code never pushes openers, pushes closers as unresolved openers, or overwrites one scalar instead of preserving nesting.","roles":["stack","opening bracket","input scan","unmatched openers"],"mustProve":["The code scans the input characters.","Opening brackets are stored in the LIFO stack for later closer checks.","The pushed stack item represents the opener itself or an equivalent opener type, not an unrelated index."],"mustNotAccept":["Using a plain count per bracket type.","Overwriting one scalar instead of preserving nesting.","Pushing closing brackets as unresolved openers."],"equivalentVariants":["Use `stack.append(char)` for opener characters.","Use an equivalent LIFO push operation."],"proofSnippets":[{"id":"py-valid-parentheses-push-openers","language":"python","code":"def isValid(s: str) -> bool:\n    stack = []\n    for char in s:\n        if char in ['(', '[', '{']:\n            stack.append(char)\n    return True"}],"semanticFactNote":"This proves a LIFO push of the current opener during the scan."}},{"id":"mapping","title":"Encode bracket pairs","description":"Encode the compatibility relation between each closing bracket and its matching opening bracket.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"initializes_delimiter_pair_map","scope":"mapping","readMode":"stack-value-query-v1"}]},"commonMistakes":["Mapping openers to closers and then checking the wrong direction","Forgetting one bracket type"],"hint":"A closer-to-opener map keeps the compatibility check direct.","semanticSpec":{"intent":"Encode bracket compatibility so each closer has a known matching opener.","doneWhen":"This step is done when the code represents the three closer-to-opener bracket pairs.","shouldFailWhen":"This step should fail if one bracket type is missing or if the relation cannot distinguish the supported bracket types.","roles":["closing bracket","expected opening bracket","delimiter relation"],"mustProve":["Every supported closing bracket has a corresponding opening bracket relation."],"mustNotAccept":["Only counting bracket frequencies.","Omitting a delimiter type.","Using a relation that cannot distinguish `]` from `)`."],"equivalentVariants":["Use a closer-to-opener map.","Use an opener-to-closer map together with an equivalent top-of-stack comparison.","Use explicit same-type branches for the three supported bracket pairs."],"neededLowerLayerFact":{"suggestedFamily":"stack","suggestedFact":"defines_delimiter_pair_relation","suggestedScope":"mapping","owner":"Layer 5A LIFO/delimiter structural fact plus Layer 6 stack fact reader"},"proofSnippets":[{"id":"py-valid-parentheses-mapping","language":"python","code":"def isValid(s: str) -> bool:\n    stack = []\n    pairs = {')': '(', ']': '[', '}': '{'}\n    for char in s:\n        if char in ['(', '[', '{']:\n            stack.append(char)\n    return pairs[')'] == '('"}]}},{"id":"validate-closers","title":"Route closing brackets to validation","description":"When the current character is a closing bracket, handle it through closer-validation logic.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"branches_on_delimiter_closer_membership","scope":"validate-closers","readMode":"stack-value-query-v1"}]},"commonMistakes":["Treating every character as an opener","Checking closers after pushing them"],"hint":"The closer branch should run before any opener push.","semanticSpec":{"intent":"Detect closing brackets and send them to validation instead of pushing them as openers.","doneWhen":"This step is done when the scan branches on whether the current character is one of the closing delimiters.","shouldFailWhen":"This step should fail if closing brackets are pushed as openers or if the closer branch is missing.","roles":["closing bracket","delimiter relation","input scan"],"mustProve":["The scan distinguishes closers from openers.","Closer characters enter a validation branch before opener push logic."],"mustNotAccept":["Pushing every character.","Treating all non-empty-stack cases as valid."],"equivalentVariants":["Use `if char in pairs:` for closer handling.","Use an equivalent closer-set membership branch."],"neededLowerLayerFact":{"suggestedFamily":"stack","suggestedFact":"branches_on_delimiter_closer_membership","suggestedScope":"validate-closers","owner":"Layer 5A delimiter structural fact plus Layer 6 stack fact reader"},"proofSnippets":[{"id":"py-valid-parentheses-closer-branch","language":"python","code":"def isValid(s: str) -> bool:\n    stack = []\n    pairs = {')': '(', ']': '[', '}': '{'}\n    for char in s:\n        if char in pairs:\n            return pairs[char] == '('\n        if char in ['(', '[', '{']:\n            stack.append(char)"}]}},{"id":"reject-bad-closers","title":"Reject empty or mismatched closers","description":"For a closing bracket, reject if no opener is waiting or if the top opener has the wrong type.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"rejects_empty_or_mismatched_delimiter_top","scope":"reject-bad-closers","readMode":"stack-value-query-v1"}]},"commonMistakes":["Popping from an empty stack","Searching any previous opener instead of checking the top"],"hint":"The most recent unmatched opener must match this closer.","semanticSpec":{"intent":"Reject closer characters that cannot match the current stack top.","doneWhen":"This step is done when closer handling returns false if the stack is empty or if the closing bracket does not match the current stack top.","shouldFailWhen":"This step should fail if the code pops before checking, searches the whole stack, or accepts crossed pairs like `([)]`.","roles":["closing bracket","stack top","matching bracket pair","failure return"],"mustProve":["Closer handling checks that an opener is available.","The checked opener is the most recent unmatched opener.","The closer is validated against the bracket type of that stack top.","A mismatch returns false before accepting the closer."],"mustNotAccept":["Searching the whole stack for a match.","Popping before confirming the stack is non-empty.","Accepting crossed pairs like `([)]`."],"equivalentVariants":["Map closers to expected openers and compare that expected opener with the stack top.","Map openers to expected closers and compare the current closer with the closer expected by the stack top.","Use conditional or switch-style pair checks, as long as the current closer is matched against only the stack top.","Use an equivalent pop-and-compare form that still rejects empty stacks safely."],"neededLowerLayerFact":{"suggestedFamily":"stack","suggestedFact":"rejects_empty_or_mismatched_delimiter_top","suggestedScope":"reject-bad-closers","owner":"Layer 5A relational LIFO top-check fact plus Layer 6 stack fact reader"},"proofSnippets":[{"id":"py-valid-parentheses-reject-bad-closers","language":"python","code":"def isValid(s: str) -> bool:\n    stack = []\n    pairs = {')': '(', ']': '[', '}': '{'}\n    for char in s:\n        if char in pairs:\n            if not stack or stack[-1] != pairs[char]:\n                return False\n        elif char in ['(', '[', '{']:\n            stack.append(char)"}]}},{"id":"pop-matched-openers","title":"Pop matched openers","description":"After a closer matches the stack top, remove that opener from the stack.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"pops_matched_delimiter_top","scope":"pop-matched-openers","readMode":"stack-value-query-v1"}]},"commonMistakes":["Leaving matched openers on the stack","Removing more than one opener"],"hint":"A matched opener is no longer unmatched.","semanticSpec":{"intent":"Consume the matched opener exactly once after closer validation succeeds.","doneWhen":"This step is done when the closer branch pops the stack only after the top opener is known to match.","shouldFailWhen":"This step should fail if the code never pops matched openers, pops before checking the match, or pops multiple openers for one closer.","roles":["matched opener","closing bracket","pop","stack top"],"mustProve":["A matched closer removes the most recent opener.","The pop occurs after the closer has been accepted as matching."],"mustNotAccept":["Leaving matched openers on the stack.","Popping before mismatch rejection.","Removing an arbitrary opener instead of the top."],"equivalentVariants":["Use `stack.pop()` after the mismatch guard.","Use `stack.pop() != pairs[ch]` if empty-stack safety is already handled."],"neededLowerLayerFact":{"suggestedFamily":"stack","suggestedFact":"pops_matched_delimiter_top","suggestedScope":"pop-matched-openers","owner":"Layer 5A relational LIFO pop fact plus Layer 6 stack fact reader"},"proofSnippets":[{"id":"py-valid-parentheses-pop-matched-openers","language":"python","code":"def isValid(s: str) -> bool:\n    stack = []\n    pairs = {')': '(', ']': '[', '}': '{'}\n    for char in s:\n        if char in pairs:\n            if not stack or stack[-1] != pairs[char]:\n                return False\n            stack.pop()\n        else:\n            stack.append(char)"}]}},{"id":"empty-at-end","title":"Require an empty stack","description":"After scanning all characters, return true only if no openers remain.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"stack","fact":"returns_empty_stack_state","scope":"empty-at-end","readMode":"stack-value-query-v1"}]},"commonMistakes":["Returning true after the loop even with leftover openers","Forgetting strings like \"((\""],"hint":"A valid string closes every opener.","semanticSpec":{"intent":"Return true only when the scan finishes with no unmatched opening brackets left on the stack.","doneWhen":"This step is done when the terminal return is based on stack emptiness after all characters have been processed.","shouldFailWhen":"This step should fail if the function always returns true after the loop, ignores leftover openers, or returns true before scanning the whole string.","roles":["terminal return","stack emptiness","unmatched openers","full scan"],"mustProve":["The input scan has completed.","The returned validity condition requires the opener stack to be empty."],"mustNotAccept":["Returning true with leftover openers.","Returning true immediately after the first matched pair.","Checking only opener and closer counts."],"equivalentVariants":["Use `return not stack`.","Use `return len(stack) == 0` after the loop."],"neededLowerLayerFact":{"suggestedFamily":"stack","suggestedFact":"returns_success_only_on_empty_lifo_state","suggestedScope":"empty-at-end","owner":"Layer 5A terminal LIFO state return fact plus Layer 6 stack fact reader"},"proofSnippets":[{"id":"py-valid-parentheses-empty-end","language":"python","code":"def isValid(s: str) -> bool:\n    stack = []\n    pairs = {')': '(', ']': '[', '}': '{'}\n    for char in s:\n        if char in pairs:\n            if not stack or stack[-1] != pairs[char]:\n                return False\n            stack.pop()\n        else:\n            stack.append(char)\n    return not stack"}]}}],"version":2,"slides":[{"id":"the-task","chapter":"The problem","kind":"info","eyebrow":"Read the problem","title":"Brackets that close in the right order","workspacePanel":"problem","body":["A string of brackets is valid when every opener is closed by a closer of its own kind, and no two pairs cross each other.","Two things have to hold at once: the kinds have to match, and the order has to work out. It is easy to write a check that only notices one of them."]},{"id":"counter-fails","chapter":"The problem","kind":"code-trace","eyebrow":"The obvious way","title":"Just count the brackets?","summary":"Count up on every opener, down on every closer, and check it lands back at zero. That does reject strings with too many of one side. It also accepts ([)], which has one of each and balances perfectly.","workspacePanel":"trace","body":["A single counter: +1 for an opener, -1 for a closer, never dipping below zero, and zero at the end."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"balance = 0\nfor char in s:\n    if char in \"([{\":\n        balance += 1\n    else:\n        balance -= 1\n        if balance < 0:\n            return False\nreturn balance == 0","steps":[{"id":"counter-climbs","title":"The counter climbs honestly","codeLine":4,"summary":"s = \"([)]\". The ( and [ each add one: balance is 2. So far the count is climbing exactly as it should.","state":{"s":"([)]","i":1,"balance":2,"labels":{"i":"char"}}},{"id":"wrong-match-counted","title":"The ) pays down the wrong debt","codeLine":6,"summary":"The ) subtracts one. The counter cannot know the pending opener was [, a number has no idea which bracket it is counting.","state":{"s":"([)]","i":2,"balance":1,"labels":{"i":"char"}}},{"id":"certified-garbage","title":"Balanced, and wrong","codeLine":9,"summary":"The ] brings balance to 0 and the function returns True for a string whose brackets interleave illegally. The bug is invisible on single-type inputs, which is how it survives casual testing.","state":{"s":"([)]","i":3,"balance":0,"labels":{"i":"char"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let balance = 0;\nfor (const char of s) {\n    if (\"([{\".includes(char)) {\n        balance++;\n    } else {\n        balance--;\n        if (balance < 0) {\n            return false;\n        }\n    }\n}\nreturn (balance === 0);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":12},"statementBundles":{"8":{"startLine":8,"endLine":11}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let balance = 0;\nfor (const char of s) {\n    if (\"([{\".includes(char)) {\n        balance++;\n    } else {\n        balance--;\n        if (balance < 0) {\n            return false;\n        }\n    }\n}\nreturn (balance === 0);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":12},"statementBundles":{"8":{"startLine":8,"endLine":11}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int balance = 0;\nfor (char char_ : s.toCharArray()) {\n    if (\"([{\".contains(String.valueOf(char_))) {\n        balance++;\n    } else {\n        balance--;\n        if (balance < 0) {\n            return false;\n        }\n    }\n}\nreturn balance == 0;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":12},"statementBundles":{"8":{"startLine":8,"endLine":11}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int balance = 0;\nforeach (char char_ in s) {\n    if (\"([{\".Contains(char_.ToString())) {\n        balance++;\n    } else {\n        balance--;\n        if (balance < 0) {\n            return false;\n        }\n    }\n}\nreturn balance == 0;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":12},"statementBundles":{"8":{"startLine":8,"endLine":11}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int balance = 0;\nfor (char ch : s) {\n    if (string(\"([{\").find(ch) != string::npos) {\n        balance++;\n    } else {\n        balance--;\n        if (balance < 0) {\n            return false;\n        }\n    }\n}\nreturn (balance == 0);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":12},"statementBundles":{"8":{"startLine":8,"endLine":11}}}}}},{"id":"what-counting-misses","chapter":"The problem","kind":"case-probe","eyebrow":"Name the gap","title":"What did counting lose?","workspacePanel":"trace","options":[{"id":"order","label":"Order, when the ) arrived, the newest unclosed opener was [, not (","rationale":"A count says how many brackets are open, never which one is next to close. Validity turns on the identity of the pending opener, positional information a single number cannot hold.","isCorrect":true},{"id":"counts-unequal","label":"Nothing, the counts are actually unequal","rationale":"One of each bracket: every count balances. That is exactly why a counter waves ([)] through.","isCorrect":false},{"id":"per-type","label":"It just needs one counter per bracket type","rationale":"Three counters still balance on ([)], each type opens once and closes once. No count captures which opener is currently on top.","isCorrect":false}],"answer":"Counting forgets opener identity and nesting order. The scan needs to keep the unmatched openers in the order they arrived.","summary":"([)] balanced every count, yet it is invalid."},{"id":"recency-invariant","chapter":"The idea","kind":"case-probe","eyebrow":"Name the rule","title":"Which opener must a closer match?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"recency-state","state":{"s":"([)]","i":2,"stack":["(","["],"labels":{"i":"char"}}}]},"options":[{"id":"newest","label":"Only the most recently opened one still waiting","rationale":"Nesting means the newest opener must finish first. Keep the openers newest-on-top and the next legal match is always the one on top, that structure is a stack.","isCorrect":true},{"id":"any-same-type","label":"Any waiting opener of the same type, anywhere in the memory","rationale":"Reaching past the top to match a deeper opener slices through the brackets between them, exactly the ([)] disorder. Only the newest may close.","isCorrect":false},{"id":"oldest","label":"The oldest opener, the first one that was added","rationale":"Closing the oldest first is nesting in reverse. In ([]) the inner ] closes before the outer ), newest-first, never oldest.","isCorrect":false}],"answer":"A closer may only match the newest unmatched opener. Storing openers newest-on-top makes 'the next required match' always the top, a stack.","summary":"Keep a memory of the unmatched openers as they arrive."},{"id":"single-check-probe","chapter":"The idea","kind":"case-probe","eyebrow":"Name the rule","title":"What is the entire check?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-check-state","state":{"s":"([)]","i":2,"stack":["(","["],"stackActive":[1],"labels":{"i":"char"}}}]},"options":[{"id":"pop-compare-top","label":"Pop the top and compare, the newest opener is the only one allowed to close now","rationale":"Nesting means the latest opener must finish first. One pop, one comparison; anything else on the stack is legally unreachable.","isCorrect":true},{"id":"search-stack","label":"Search the stack for a matching opener","rationale":"Finding a match deeper down is exactly the invalid case, the brackets between would be cut open. Depth search is not just slow here; it is wrong.","isCorrect":false},{"id":"decrement","label":"Decrement the right counter","rationale":"A counter cannot carry which opener is waiting, or in what order.","isCorrect":false}],"answer":"Pop, compare, done. The top of the stack is not the best candidate, it is the only candidate.","summary":"A closing bracket arrives while the stack holds unmatched openers."},{"id":"pop-without-match-pitfall","chapter":"The idea","kind":"pitfall","eyebrow":"Spot the trap","title":"Does a closer even need to check what it pops?","summary":"Every closer cancels one opener, so on a closer this version just pops the top and moves on. It accepts every well-formed string and rejects a stray closer on an empty stack. On ([)] each closer pops an opener of the wrong kind and nothing catches it.","workspacePanel":"trace","pitfall":"The code below pops the stack top on every closer but never confirms the popped opener matches the closer's type.","example":"s = \"([)]\"\npush ( , push [\n)  -> pop [ , no type check, keep going\n]  -> pop ( , no type check, keep going\nstack is empty at the end -> returns True","whyItMatters":"A pop alone only counts that an opener was waiting. The accepted closer must consume an opener of its own kind, so the popped top has to be compared to the closer before it is allowed to cancel it.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"stack = [\"\"][:0]\nfor char in s:\n    if char in \")]}\":\n        if len(stack) == 0:\n            return False\n        stack.pop()\n    elif char in \"([{\":\n        stack.append(char)\nreturn len(stack) == 0","steps":[{"id":"push-both-openers","title":"Both openers go on the stack","summary":"The ( and [ are pushed in turn, so the stack holds ( on the bottom and [ on top.","codeLine":8,"state":{"s":"([)]","i":1,"stack":["(","["],"stackActive":[1],"labels":{"i":"char"}}},{"id":"pop-skips-the-check","title":"The ) pops [ without looking at it","summary":"The ) arrives with [ on top. This version pops [ and never asks whether ) closes a [. The wrong-kind match passes unnoticed.","codeLine":6,"state":{"s":"([)]","i":2,"stack":["("],"stackActive":[0],"labels":{"i":"char"}}},{"id":"second-pop-empties","title":"The ] pops ( and the stack empties","summary":"The ] pops the remaining (, again without a type check. The stack is now empty with every character consumed.","codeLine":6,"state":{"s":"([)]","i":3,"stack":[],"labels":{"i":"char"}}},{"id":"empty-accepts-garbage","title":"Empty at the end, so it says valid","summary":"An empty stack returns True, certifying ([)] as valid even though every closer matched the wrong opener. Counting pops is not the same as matching types.","codeLine":9,"state":{"s":"([)]","i":3,"stack":[],"valid":true,"labels":{"i":"char"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const stack = [\"\"].slice(0, 0);\nfor (const char of s) {\n    if (\")]}\".includes(char)) {\n        if (stack.length === 0) {\n            return false;\n        }\n        stack.pop();\n    } else {\n        if (\"([{\".includes(char)) {\n            stack.push(char);\n        }\n    }\n}\nreturn (stack.length == 0);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":9,"8":10,"9":14},"statementBundles":{"5":{"startLine":5,"endLine":6},"6":{"startLine":7,"endLine":8},"8":{"startLine":10,"endLine":13}},"alternateStyles":{"close-to-source":{"code":"const stack = [\"\"].slice(0, 0);\nfor (const char of s) {\n    if (\")]}\".includes(char)) {\n        if (stack.length === 0) {\n            return false;\n        }\n        const poppedValue = stack.pop();\n        if (poppedValue === undefined) throw new Error(\"IndexError\");\n    } else {\n        if (\"([{\".includes(char)) {\n            stack.push(char);\n        }\n    }\n}\nreturn (stack.length == 0);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":10,"8":11,"9":15},"statementBundles":{"5":{"startLine":5,"endLine":6},"6":{"startLine":7,"endLine":9},"8":{"startLine":11,"endLine":14}}}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const stack = [\"\"].slice(0, 0);\nfor (const char of s) {\n    if (\")]}\".includes(char)) {\n        if (stack.length === 0) {\n            return false;\n        }\n        stack.pop();\n    } else {\n        if (\"([{\".includes(char)) {\n            stack.push(char);\n        }\n    }\n}\nreturn (stack.length == 0);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":9,"8":10,"9":14},"statementBundles":{"5":{"startLine":5,"endLine":6},"6":{"startLine":7,"endLine":8},"8":{"startLine":10,"endLine":13}},"alternateStyles":{"close-to-source":{"code":"const stack = [\"\"].slice(0, 0);\nfor (const char of s) {\n    if (\")]}\".includes(char)) {\n        if (stack.length === 0) {\n            return false;\n        }\n        const poppedValue = stack.pop();\n        if (poppedValue === undefined) throw new Error(\"IndexError\");\n    } else {\n        if (\"([{\".includes(char)) {\n            stack.push(char);\n        }\n    }\n}\nreturn (stack.length == 0);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":10,"8":11,"9":15},"statementBundles":{"5":{"startLine":5,"endLine":6},"6":{"startLine":7,"endLine":9},"8":{"startLine":11,"endLine":14}}}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<String> stack = new ArrayList<String>(new ArrayList<>(Arrays.asList(\"\")).subList(0, 0));\nfor (char char_ : s.toCharArray()) {\n    if (\")]}\".contains(String.valueOf(char_))) {\n        if (stack.isEmpty()) {\n            return false;\n        }\n        stack.remove(stack.size() - 1);\n    } else {\n        if (\"([{\".contains(String.valueOf(char_))) {\n            stack.add(String.valueOf(char_));\n        }\n    }\n}\nreturn stack.isEmpty();","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":9,"8":10,"9":14},"statementBundles":{"5":{"startLine":5,"endLine":6},"6":{"startLine":7,"endLine":8},"8":{"startLine":10,"endLine":13}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<string> stack = new List<string> { \"\" }.GetRange(0, 0);\nforeach (char char_ in s) {\n    if (\")]}\".Contains(char_.ToString())) {\n        if (stack.Count == 0) {\n            return false;\n        }\n        stack.RemoveAt(stack.Count - 1);\n    } else {\n        if (\"([{\".Contains(char_.ToString())) {\n            stack.Add(char_.ToString());\n        }\n    }\n}\nreturn stack.Count == 0;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":9,"8":10,"9":14},"statementBundles":{"5":{"startLine":5,"endLine":6},"6":{"startLine":7,"endLine":8},"8":{"startLine":10,"endLine":13}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<string> stack_ = vector<string>(vector<string>{\"\"}.begin() + 0, vector<string>{\"\"}.begin() + 0);\nfor (char ch : s) {\n    if ((string(\")]}\").find(ch) != string::npos)) {\n        if (stack_.empty()) {\n            return false;\n        }\n        stack_.pop_back();\n    } else {\n        if (string(\"([{\").find(ch) != string::npos) {\n            stack_.push_back(string(1, ch));\n        }\n    }\n}\nreturn (stack_.size() == 0);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":9,"8":10,"9":14},"statementBundles":{"5":{"startLine":5,"endLine":6},"6":{"startLine":7,"endLine":8},"8":{"startLine":10,"endLine":13}}}}}},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the referee","title":"Trace the two ways to fail","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"mismatch-fail","state":{"s":"([)]","i":2,"stack":["(","["],"stackActive":[1],"labels":{"i":"char"}}},{"id":"leftover-fail","state":{"s":"()(","i":2,"stack":["("],"stackActive":[0],"labels":{"i":"char"}}}]},"beats":[{"id":"mismatch-fail","title":"Can a later character repair this mismatch?","summary":"On \"([)]\", the ( and [ are pushed; now the ) arrives with [ on top.","prompt":"The top-only rule proves this ) cannot close the [. Could anything later in the string make the prefix valid again?","options":[{"id":"pop-mismatch-false","label":"Pop the [ , see it is not ( , return False on the spot","rationale":"The ) claims to close something, the only legal candidate is the newest opener, and it is the wrong kind. No later character can repair a broken nesting.","isCorrect":true},{"id":"keep-looking","label":"Leave the [ and match the ( underneath","rationale":"Matching past the top would cut the [ open in the middle, the exact disorder this problem rejects.","isCorrect":false},{"id":"wait-and-see","label":"Note the mismatch and continue scanning","rationale":"A nesting violation is final. Scanning on can only waste time confirming a verdict already reached.","isCorrect":false}],"answer":"Pop, mismatch, False, at index 2, with half the string unread. The stack catches what every counter certifies."},{"id":"leftover-fail","title":"After the loop, what's the verdict?","summary":"Different string: \"()(\" scans to the end without a single mismatch.","prompt":"A different string, \"()(\", reaches the end with no mismatch.","options":[{"id":"leftover-false","label":"False, an unclosed opener is a failure that only the end can see","rationale":"No character contradicted anything, but a promise went unkept. Validity is decided by an empty stack at the end, not by surviving the loop.","isCorrect":true},{"id":"no-mismatch-true","label":"True, nothing ever mismatched","rationale":"Validity needs both: no bad closers and no abandoned openers. The second condition lives after the loop.","isCorrect":false},{"id":"depends-type","label":"Depends on which bracket is left over","rationale":"Any leftover opener means an unclosed bracket, the type changes nothing about the verdict.","isCorrect":false}],"answer":"An empty stack at the end means valid; a leftover opener means invalid. Two failure modes in two places: a mismatch fails inside the loop, a leftover fails after it."}]},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Matching each closer against the newest opener holds up on well-formed strings. A scan like this is easiest to break on the shortest, oddest inputs, where the stack barely fills.","Two are worth a look before coding: a string that opens with a closer, and the empty string."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"s":"([)]","i":2,"stack":["(","["],"stackActive":[1],"labels":{"i":"char"}}}]}},{"id":"leading-closer-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"What stops a pop when nothing's open?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"leading-closer-state","state":{"s":")(","i":0,"stack":[],"labels":{"i":"char"}}}]},"options":[{"id":"not-stack-guard","label":"The empty-stack check, it rejects the closer before any pop is attempted","rationale":"An empty stack means no opener is owed, so a closer arriving anyway is invalid on its face. Checking first turns a would-be crash into a clean verdict.","isCorrect":true},{"id":"pop-none","label":"Popping anyway sorts itself out, there is nothing to compare against","rationale":"Popping an empty stack has nothing to return; the empty check turns that case into a clean false result.","isCorrect":false},{"id":"cannot-happen","label":"Nothing, inputs never start with a closer","rationale":"\")(\" is a legal input string. The contract restricts the alphabet and allows any order.","isCorrect":false}],"answer":"Check for an empty stack before trying to pop. With nothing owed, a closer is wrong on arrival, and the same check also catches a closer that pops the wrong kind of opener.","summary":"s = \")(\" starts with a closer."},{"id":"empty-string-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"Is an empty string valid?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"empty-string-state","state":{"s":"","i":0,"stack":[],"labels":{"i":"char"}}}]},"options":[{"id":"vacuous-true","label":"True, zero brackets break zero rules","rationale":"Validity is the absence of violations, and the empty string commits none. The end-check answers it with no special case.","isCorrect":true},{"id":"empty-invalid","label":"False, there is nothing valid about it","rationale":"Every rule is of the form \"every opener must...\", with no openers, every rule is satisfied vacuously. Empty passes.","isCorrect":false},{"id":"guard-needed","label":"It should be special-cased before the loop","rationale":"The special case would return the same True the last line already produces. Structure over patches, again.","isCorrect":false}],"answer":"An empty stack after an empty scan: True. The final check was built for leftovers and handles nothingness for free.","summary":"s = \"\", no brackets at all, so nothing is ever pushed."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"The stack answers which opener is next; three checks decide the verdict.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"s":"([)]","stack":[]}}]},"body":["Walk the string keeping a stack of openers still waiting to be closed. Each closer must answer to the most recent opener, so the stack is what lets you check recency.","Two things can go wrong as you go, and one more once the walk ends: a closer with nothing owed, a closer matched to the wrong kind, and openers still left waiting at the finish."]},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build the bracket referee","summary":"Now build it: push each opener, and on a closer reject an empty stack or a wrong-type top before popping the match, then accept only if nothing is left waiting.","workspacePanel":"code"},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","summary":"Nesting is recency: the newest opener is the only legal next close.","workspacePanel":"code","body":["A stack can act as an order referee: the next action always concerns the newest entry, never anything buried beneath it.","The counter is the lesson worth keeping. A total can only tell you how many, and this problem was never about how many."],"takeaways":[{"title":"Top is the only candidate","body":"A closer may only match the newest unmatched opener. Pop and compare, searching deeper would itself be the violation."},{"title":"Two failure modes, two exits","body":"Bad closers fail inside the loop (mismatch or empty stack); abandoned openers fail after it. `return not stack` is half the correctness."},{"title":"Counters lose identity","body":"\"([)]\" balances every count and is invalid. When the rule is about which and in what order, the state must store the things, not their tally."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"},"executionStyle":"solution-method","syntheticTestConfig":{"inputShape":"string","primaryParam":"s","sizeMetric":"length","alphabet":"()[]{}"}}
