Skip to Content

Longest valid parentheses

Home | Coding Interviews | Stacks and Queues | Longest valid parentheses

Given a string containing just the characters '(' and ')', return the length of the longest valid (well-formed) parentheses substring.

class Solution:
    def longestValidParentheses(self, s: str) -> int:

        # stack, used to record index of parenthesis
        # initialized to -1 as dummy head for valid parentheses length computation
        stack = [-1]
        
        max_length = 0
        
		# linear scan each index and character in input string s
        for cur_idx, char in enumerate(s):
            
            if char == '(':
                
                # push when current char is (
                stack.append( cur_idx )
                
            else:
                
                # pop when current char is )
                stack.pop()
                
                if not stack:
                    
                    # stack is empty, push current index into stack
                    stack.append( cur_idx )
                else:
                    # stack is non-empty, update maximal valid parentheses length
                    max_length = max(max_length, cur_idx - stack[-1])
                
        return max_length

It is also possible to solve without a stack

class Solution:
    def longestValidParentheses(self, s: str) -> int:
        max_length = 0
                
        l,r=0,0        
        # traverse the string from left to right
        for i in range(len(s)):
            if s[i] == '(':
                l+=1
            else:
                r+=1                        
            if l == r:# valid balanced parantheses substring 
                max_length=max(max_length, l*2)
            elif r>l: # invalid case as ')' is more
                l=r=0
        
        l,r=0,0        
        # traverse the string from right to left
        for i in range(len(s)-1,-1,-1):
            if s[i] == '(':
                l+=1
            else:
                r+=1            
            if l == r:# valid balanced parantheses substring 
                max_length=max(max_length, l*2)
            elif l>r: # invalid case as '(' is more
                l=r=0
        return max_length

Posted by Jamie Meyer 18 days ago