{"id":27417,"date":"2018-02-05T21:42:27","date_gmt":"2018-02-05T16:12:27","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27417"},"modified":"2018-02-05T21:42:27","modified_gmt":"2018-02-05T16:12:27","slug":"python-algorithm-length-longest-valid-substring","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/python-algorithm-length-longest-valid-substring\/","title":{"rendered":"Python Algorithm &#8211; Length of the longest valid substring"},"content":{"rendered":"<p>Given a string consisting of opening and closing parenthesis, find length of the longest valid parenthesis substring.<\/p>\n<p>Examples:<\/p>\n<pre>Input : ((()\r\nOutput : 2\r\nExplanation : ()\r\n\r\nInput: )()())\r\nOutput : 4\r\nExplanation: ()() \r\n\r\nInput:  ()(()))))\r\nOutput: 6\r\nExplanation:  ()(()))\r\n<\/pre>\n<p><b>We strongly recommend you to minimize your browser and try this yourself first.<\/b><\/p>\n[ad type=&#8221;banner&#8221;]\n<p>A <strong>Simple Approach<\/strong> is to find all the substrings of given string. For every string, check if it is a valid string or not. If valid and length is more than maximum length so far, then update maximum length. We can check whether a substring is valid or not in linear time using a stack (See this for details). Time complexity of this solution is O(n<sup>2<\/sup>.<\/p>\n<p>An <strong>Efficient Solution<\/strong> can solve this problem in O(n) time. The idea is to store indexes of previous starting brackets in a stack. The first element of stack is a special element that provides index before beginning of valid substring (base for next valid string).<\/p>\n<pre>1) Create an empty stack and push -1 to it. The first element\r\n   of stack is used to provide base for next valid string. \r\n\r\n2) Initialize result as 0.\r\n\r\n3) If the character is '(' i.e. str[i] == '('), push index \r\n   'i' to the stack. \r\n   \r\n2) Else (if the character is ')')\r\n   a) Pop an item from stack (Most of the time an opening bracket)\r\n   b) If stack is not empty, then find length of current valid\r\n      substring by taking difference between current index and\r\n      top of the stack. If current length is more than result,\r\n      then update the result.\r\n   c) If stack is empty, push current index as base for next\r\n      valid substring.\r\n\r\n3) Return result.<\/pre>\n<p>Below are Python implementations of above algorithm.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Python Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># Python program to find length of the longest valid<br\/># substring<br\/> <br\/>def findMaxLen(string):<br\/>    n = len(string)<br\/> <br\/>    # Create a stack and push -1 as initial index to it.<br\/>    stk = []<br\/>    stk.append(-1)<br\/> <br\/>    # Initialize result<br\/>    result = 0<br\/> <br\/>    # Traverse all characters of given string<br\/>    for i in xrange(n):<br\/>     <br\/>        # If opening bracket, push index of it<br\/>        if string[i] == &#039;(&#039;:<br\/>            stk.append(i)<br\/> <br\/>        else:    # If closing bracket, i.e., str[i] = &#039;)&#039;<br\/>     <br\/>            # Pop the previous opening bracket&#039;s index<br\/>            stk.pop()<br\/>     <br\/>            # Check if this length formed with base of<br\/>            # current valid substring is more than max <br\/>            # so far<br\/>            if len(stk) != 0:<br\/>                result = max(result, i - stk[len(stk)-1])<br\/> <br\/>            # If stack is empty. push current index as <br\/>            # base for next valid substring (if any)<br\/>            else:<br\/>                stk.append(i)<br\/> <br\/>    return result<br\/> <br\/># Driver program<br\/>string = &quot;((()()&quot;<br\/>print findMaxLen(string)<br\/> <br\/>string = &quot;()(()))))&quot;<br\/>print findMaxLen(string)<br\/> <br\/># This code is contributed by Bhavya Jain<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>4\r\n6<\/pre>\n<p><strong>Explanation with example:<\/strong><\/p>\n<pre>Input: str = \"(()()\"\r\n\r\nInitialize result as 0 and stack with one item -1.\r\n\r\nFor i = 0, str[0] = '(', we push 0 in stack\r\n\r\nFor i = 1, str[1] = '(', we push 1 in stack\r\n\r\nFor i = 2, str[2] = ')', currently stack has [-1, 0, 1], we pop\r\nfrom the stack and the stack now is [-1, 0] and length of current\r\nvalid substring becomes 2 (we get this 2 by subtracting stack top \r\nfrom current index).\r\nSince current length is more than current result, we update result.\r\n\r\nFor i = 3, str[3] = '(', we push again, stack is [-1, 0, 3].\r\n\r\nFor i = 4, str[4] = ')', we pop from the stack, stack becomes \r\n[-1, 0] and length of current valid substring becomes 4 (we get \r\nthis 4 by subtracting stack top from current index). \r\nSince current length is more than current result, we update result.<\/pre>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p> Python Algorithm &#8211; Length of the longest valid substring &#8211; Stack &#8211;  Given a string consisting of opening and closing parenthesis<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[73012,4148,79607],"tags":[81547,81549,81545,81544,81543,81546,81567,81548],"class_list":["post-27417","post","type-post","status-publish","format-standard","hentry","category-data-structures","category-python","category-stack","tag-balanced-parentheses-dynamic-programming","tag-find-the-longest-substring-without-any-number-and-at-least-one-upper-case-character","tag-longest-subsequence-of-balanced-parentheses","tag-longest-parentheses-substring-java","tag-longest-valid-parentheses-leetcode-c","tag-longest-valid-parentheses-youtube","tag-minimum-size-subarray-sum-java","tag-modify-the-array"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27417","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=27417"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27417\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27417"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27417"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27417"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}