{"id":10596,"date":"2026-11-29T08:00:46","date_gmt":"2026-11-29T08:00:46","guid":{"rendered":"https:\/\/cybersecurityinfocus.com\/?p=10596"},"modified":"2026-11-29T08:00:46","modified_gmt":"2026-11-29T08:00:46","slug":"valid-parentheses-in-python-from-brute-force-to-stack","status":"publish","type":"post","link":"https:\/\/cybersecurityinfocus.com\/?p=10596","title":{"rendered":"Valid Parentheses in Python: From Brute Force to Stack"},"content":{"rendered":"<p class=\"wp-block-paragraph\">Easy \u00b7 Stack \u00b7 Strings \u00b7 LeetCode 20. Imagine checking whether every opened box is closed in reverse order. A stack remembers the most recently opened bracket.<\/p>\n<p>Stack walkthrough: ([{}]) \u2014 push three openers, then pop three matching closers.<\/p>\n<h2 class=\"wp-block-heading\">1. Problem and constraints<\/h2>\n<p class=\"wp-block-paragraph\">Given a string containing only (), [], and {}, return true if each opening bracket is closed by the same type in the correct order. Length: 1 to 10,000.<\/p>\n<p class=\"wp-block-paragraph\">Examples: ()[]{} \u2192 True; ([{}]) \u2192 True; (] \u2192 False; ([)] \u2192 False.<\/p>\n<h2 class=\"wp-block-heading\">2. Progressive hints<\/h2>\n<p class=\"wp-block-paragraph\">Hint 1: Adjacent matching pairs can be removed. Hint 2: The last opening bracket must close first. Hint 3: Use a LIFO stack.<\/p>\n<h2 class=\"wp-block-heading\">3. Brute-force approach<\/h2>\n<p class=\"wp-block-paragraph\">Repeatedly remove adjacent matching pairs. If no more pairs can be removed, the string is valid exactly when empty.<\/p>\n<p>def valid_brute(s):<br \/>\n    while any(pair in s for pair in (&#8220;()&#8221;, &#8220;[]&#8221;, &#8220;{}&#8221;)):<br \/>\n        for pair in (&#8220;()&#8221;, &#8220;[]&#8221;, &#8220;{}&#8221;):<br \/>\n            s = s.replace(pair, &#8220;&#8221;)<br \/>\n    return not s<\/p>\n<h2 class=\"wp-block-heading\">4. Optimized stack approach<\/h2>\n<p class=\"wp-block-paragraph\">Push opening brackets. For a closing bracket, reject an empty stack or mismatched top. Accept only if the stack is empty at the end.<\/p>\n<p>FOR each character:<br \/>\n  IF opening: PUSH<br \/>\n  ELSE IF stack empty or POP does not match: RETURN false<br \/>\nRETURN stack is emptydef is_valid(s):<br \/>\n    stack = []<br \/>\n    pairs = {&#8220;)&#8221;: &#8220;(&#8220;, &#8220;]&#8221;: &#8220;[&#8220;, &#8220;}&#8221;: &#8220;{&#8220;}<br \/>\n    for ch in s:<br \/>\n        if ch in pairs:<br \/>\n            if not stack or stack.pop() != pairs[ch]:<br \/>\n                return False<br \/>\n        else:<br \/>\n            stack.append(ch)<br \/>\n    return not stack<\/p>\n<h2 class=\"wp-block-heading\">5. Dry run: ([{}])<\/h2>\n<p class=\"wp-block-paragraph\">Read ( \u2192 stack (. Read [ \u2192 stack ([. Read { \u2192 stack ([{. Read } \u2192 stack ([. Read ] \u2192 stack (. Read ) \u2192 empty. Result: True.<\/p>\n<h2 class=\"wp-block-heading\">6. Why it works<\/h2>\n<p class=\"wp-block-paragraph\">Invariant: after every successful step, the stack holds exactly the unmatched opening brackets in encounter order. A closing bracket must match the latest unmatched opener. A mismatch cannot be repaired by later characters. At the end, an empty stack means all brackets matched.<\/p>\n<h2 class=\"wp-block-heading\">7. Complexity comparison<\/h2>\n<p class=\"wp-block-paragraph\">Repeated replacement: O(n\u00b2) worst-case time, O(n) auxiliary space for intermediate strings. Stack: O(n) time and O(n) worst-case auxiliary space. Every character is processed once.<\/p>\n<h2 class=\"wp-block-heading\">8. Edge cases and testing<\/h2>\n<p class=\"wp-block-paragraph\">Test single opener, single closer, nested pairs, adjacent pairs, crossed pairs, odd lengths and deeply nested inputs. Empty input is outside the stated constraints but both functions return True.<\/p>\n<p>assert is_valid(&#8220;([{}])&#8221;)<br \/>\nassert is_valid(&#8220;()[]{}&#8221;)<br \/>\nassert not is_valid(&#8220;([)]&#8221;)<br \/>\nassert not is_valid(&#8220;]&#8221;)<br \/>\nassert not is_valid(&#8220;(&#8220;)<\/p>\n<h2 class=\"wp-block-heading\">9. Common mistakes<\/h2>\n<p class=\"wp-block-paragraph\">Do not count brackets without checking order. Do not pop an empty stack. Do not forget to check for leftover openers.<\/p>\n<h2 class=\"wp-block-heading\">10. Interview questions<\/h2>\n<p class=\"wp-block-paragraph\">Why a stack? Matching follows last-in-first-out. Can a counter replace it? Only for one bracket type with prefix validation. Can we do better than O(n) time? No, worst-case input must be inspected. What is worst-case stack size? n for all opening brackets. How to return the first error? Track indices alongside opening brackets.<\/p>\n<h2 class=\"wp-block-heading\">11. Related practice<\/h2>\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/leetcode.com\/problems\/valid-parentheses\/\" target=\"_blank\" rel=\"noopener\">Valid Parentheses<\/a> \u00b7 <a href=\"https:\/\/leetcode.com\/problems\/min-stack\/\" target=\"_blank\" rel=\"noopener\">Min Stack<\/a> \u00b7 <a href=\"https:\/\/leetcode.com\/problems\/longest-valid-parentheses\/\" target=\"_blank\" rel=\"noopener\">Longest Valid Parentheses<\/a> \u00b7 <a href=\"https:\/\/programesecure.com\/two-sum-python-hash-map\/\">Two Sum in Python<\/a><\/p>\n<h2 class=\"wp-block-heading\">12. Quick revision<\/h2>\n<p class=\"wp-block-paragraph\">Recognize nested matching as a stack problem. Push openers, match and pop closers, reject mismatches, and require an empty stack at the end.<\/p>","protected":false},"excerpt":{"rendered":"<p>Easy \u00b7 Stack \u00b7 Strings \u00b7 LeetCode 20. Imagine checking whether every opened box is closed in reverse order. A stack remembers the most recently opened bracket. Stack walkthrough: ([{}]) \u2014 push three openers, then pop three matching closers. 1. Problem and constraints Given a string containing only (), [], and {}, return true if [&hellip;]<\/p>\n","protected":false},"author":0,"featured_media":10597,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-10596","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-news"],"_links":{"self":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts\/10596"}],"collection":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"replies":[{"embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=10596"}],"version-history":[{"count":0,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts\/10596\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/media\/10597"}],"wp:attachment":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=10596"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=10596"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=10596"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}