{"id":849,"date":"2025-08-06T11:31:30","date_gmt":"2025-08-06T06:01:30","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=849"},"modified":"2025-08-06T11:32:14","modified_gmt":"2025-08-06T06:02:14","slug":"valid-parentheses","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/valid-parentheses\/","title":{"rendered":"Valid Parentheses | Leetcode 20 | Stack implementation"},"content":{"rendered":"\n<p>The\u00a0<strong>Valid Parentheses<\/strong>\u00a0problem is a classic interview question to check your understanding of stacks and string parsing. It evaluates whether a given string consisting of parentheses\u2014<code>()<\/code>,\u00a0<code>{}<\/code>,\u00a0<code>[]<\/code>, is well-formed. This guide provides a clear explanation, an easy-to-follow Python solution, and complexity analysis.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/leetcode.com\/problems\/valid-parentheses\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Problem Statement<\/h2>\n\n\n\n<p>Given a string&nbsp;<code>s<\/code>&nbsp;containing just the characters&nbsp;<code>'('<\/code>,&nbsp;<code>')'<\/code>,&nbsp;<code>'{'<\/code>,&nbsp;<code>'}'<\/code>,&nbsp;<code>'['<\/code>, and&nbsp;<code>']'<\/code>, determine if the input string is valid.<\/p>\n\n\n\n<p>An input string is valid if:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Open brackets are closed by the same type of brackets.<\/li>\n\n\n\n<li>Open brackets are closed in the correct order.<\/li>\n\n\n\n<li>Every close bracket has a corresponding open bracket.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(1 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"Input: s = &quot;()[]{}&quot;\nOutput: true\n\nInput: s = &quot;(]&quot;\nOutput: false\n\nInput: s = &quot;([)]&quot;\nOutput: false\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">Input: s = <\/span><span style=\"color: #CE9178\">&quot;()[]<\/span><span style=\"color: #569CD6\">{}<\/span><span style=\"color: #CE9178\">&quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Output: true<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Input: s = <\/span><span style=\"color: #CE9178\">&quot;(]&quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Output: false<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Input: s = <\/span><span style=\"color: #CE9178\">&quot;([)]&quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Output: false<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"intuition--approach\">Intuition &amp; Approach<\/h2>\n\n\n\n<p>The problem naturally maps to a&nbsp;<strong>stack<\/strong>&nbsp;data structure:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Every time you see an opening bracket, push it onto the stack.<\/li>\n\n\n\n<li>When you encounter a closing bracket, pop from the stack and check if it matches the corresponding opening bracket.<\/li>\n\n\n\n<li>If it matches, continue; otherwise, return false.<\/li>\n\n\n\n<li>At the end, if the stack is empty, return true (all opened brackets closed properly).<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"code-implementation\">Code Implementation<\/h2>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def isValid(self, s: str) -&gt; bool:\n        stack = []\n        \n        for bracket in s:\n            # If opening bracket, push to stack\n            if bracket in &quot;([{&quot;:\n                stack.append(bracket)\n            else:\n                # For closing bracket, stack cannot be empty\n                if len(stack) == 0:\n                    return False\n                \n                # Pop last opening bracket and check if matching\n                ch = stack.pop()\n                if (bracket == &quot;)&quot; and ch == &quot;(&quot;) or \\\n                   (bracket == &quot;]&quot; and ch == &quot;[&quot;) or \\\n                   (bracket == &quot;}&quot; and ch == &quot;{&quot;):\n                    continue\n                else:\n                    return False\n        \n        # Check if all opened brackets were closed\n        return len(stack) == 0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">isValid<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">s<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #4EC9B0\">str<\/span><span style=\"color: #D4D4D4\">) -&gt; <\/span><span style=\"color: #4EC9B0\">bool<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        stack = []<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> bracket <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> s:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># If opening bracket, push to stack<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> bracket <\/span><span style=\"color: #569CD6\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #CE9178\">&quot;([{&quot;<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                stack.append(bracket)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># For closing bracket, stack cannot be empty<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(stack) == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">False<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># Pop last opening bracket and check if matching<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                ch = stack.pop()<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> (bracket == <\/span><span style=\"color: #CE9178\">&quot;)&quot;<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> ch == <\/span><span style=\"color: #CE9178\">&quot;(&quot;<\/span><span style=\"color: #D4D4D4\">) <\/span><span style=\"color: #569CD6\">or<\/span><span style=\"color: #D4D4D4\"> \\<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                   (bracket == <\/span><span style=\"color: #CE9178\">&quot;]&quot;<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> ch == <\/span><span style=\"color: #CE9178\">&quot;[&quot;<\/span><span style=\"color: #D4D4D4\">) <\/span><span style=\"color: #569CD6\">or<\/span><span style=\"color: #D4D4D4\"> \\<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                   (bracket == <\/span><span style=\"color: #CE9178\">&quot;}&quot;<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> ch == <\/span><span style=\"color: #CE9178\">&quot;{&quot;<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    <\/span><span style=\"color: #C586C0\">continue<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">False<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Check if all opened brackets were closed<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(stack) == <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"code-explanation\">Code Explanation<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The\u00a0<code>stack<\/code>\u00a0stores unmatched opening brackets.<\/li>\n\n\n\n<li>On encountering an opening bracket (<code>(<\/code>,\u00a0<code>{<\/code>,\u00a0<code>[<\/code>), push it onto the stack.<\/li>\n\n\n\n<li>On encountering a closing bracket (<code>)<\/code>,\u00a0<code>}<\/code>,\u00a0<code>]<\/code>), pop the top element from the stack and compare. If mismatched or stack is empty, return\u00a0<code>False<\/code>.<\/li>\n\n\n\n<li>After processing the entire string, if the stack is empty, all brackets matched correctly, return\u00a0<code>True<\/code>.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"dry-run-example\">Dry Run Example<\/h2>\n\n\n\n<p>Input:&nbsp;<code>\"()[]{}\"<\/code><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>&#8216;(&#8216; \u2192 push \u2192 stack: [&#8216;(&#8216;]<\/li>\n\n\n\n<li>&#8216;)&#8217; \u2192 pop &#8216;(&#8216; \u2192 matches \u2192 continue \u2192 stack: []<\/li>\n\n\n\n<li>&#8216;[&#8216; \u2192 push \u2192 stack: [&#8216;[&#8216;]<\/li>\n\n\n\n<li>&#8216;]&#8217; \u2192 pop &#8216;[&#8216; \u2192 matches \u2192 continue \u2192 stack: []<\/li>\n\n\n\n<li>&#8216;{&#8216; \u2192 push \u2192 stack: [&#8216;{&#8216;]<\/li>\n\n\n\n<li>&#8216;}&#8217; \u2192 pop &#8216;{&#8216; \u2192 matches \u2192 continue \u2192 stack: []<br>End: stack empty \u2192 return\u00a0<code>True<\/code><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"time-and-space-complexity\">Time and Space Complexity<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time:<\/strong>\u00a0O(n), where n is the length of the string. Each character is processed once.<\/li>\n\n\n\n<li><strong>Space:<\/strong>\u00a0O(n), stack size can grow to at most n in worst case.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"conclusion\">Conclusion<\/h2>\n\n\n\n<p>Valid Parentheses is a foundational stack problem that tests your ability to match pairs and manage order efficiently. Understanding this pattern is crucial in interviews and real-world scenarios involving parsing. Practice similar problems like expression evaluation or HTML tag matching to master stack usage.<\/p>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\" target=\"_blank\" rel=\"noreferrer noopener\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\" target=\"_blank\" rel=\"noreferrer noopener\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The\u00a0Valid Parentheses\u00a0problem is a classic interview question to check your understanding of stacks and string parsing. It evaluates whether a given string consisting of parentheses\u2014(),\u00a0{},\u00a0[], is well-formed. This guide provides a clear explanation, an easy-to-follow Python solution, and complexity analysis. Here&#8217;s the [Problem Link] to begin with. Problem Statement Given a string&nbsp;s&nbsp;containing just the characters&nbsp;&#8216;(&#8216;,&nbsp;&#8216;)&#8217;,&nbsp;&#8216;{&#8216;,&nbsp;&#8216;}&#8217;,&nbsp;&#8216;[&#8216;,<\/p>\n","protected":false},"author":1,"featured_media":850,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,4],"tags":[8,37],"class_list":{"0":"post-849","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-beginner","9":"tag-easy","10":"tag-stack-and-queues"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/08\/valid-parentheses-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/849","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=849"}],"version-history":[{"count":2,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/849\/revisions"}],"predecessor-version":[{"id":861,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/849\/revisions\/861"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/850"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=849"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=849"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=849"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}