Longest valid Parentheses | Practice | GeeksforGeeks

Given a string S consisting of opening and closing parenthesis '(' and ')'. Find length of the longest valid parenthesis substring.
A parenthesis string is valid if:
For every opening parenthesis, there is a closing parenthesis.
Opening parenthesis must be closed in the correct order.
Example 1:
Input: S = ((()
Output: 2
Explaination: The longest valid 
parenthesis substring is "()".
Example 2:
Input: S = )()())
Output: 4
Explaination: The longest valid 
parenthesis substring is "()()".
Your Task:
You do not need to read input or print anything. Your task is to complete the function maxLength() which takes string S as input parameter and returns the length of the maximum valid parenthesis substring.
Expected Time Complexity: O(|S|)
Expected Auxiliary Space: O(|S|)
Constraints:
1 ≤ |S| ≤ 105  
0
chessnoobdjin 4 hours
C++ 
int maxLength(string S){
    stack <int> st;
    st.push(-1);
    int ans = 0, n = S.size();
    for(int i=0; i<n; i++){
        if(st.top() != -1 
        && S[st.top()] == '(' && S[i] == ')'){
            st.pop();
            ans = max(ans, i-st.top());
        }
        else
            st.push(i);
    }
    return ans;
}
0
mihirchavda13621 week ago
java simple solution Tc o(n) and constant space o(1)
easy to understand
 static int maxLength(String s){       int l = 0;       int r = 0;       int ans =0;       for(int i=0;i<s.length();i++){           if(s.charAt(i) == '(')               l++;           else               r++;           if(l == r)               ans = Math.max(ans , l*2);           else if(r > l){               l =0;               r =0;           }                  }       l=0;       r=0;       for(int i = s.length() -1;i >= 0;i--){           if(s.charAt(i) == '(')               l++;           else               r++;           if( l == r)               ans = Math.max(ans,l * 2);           else if(l > r){               l=0;               r=0;           }
       }       return ans;   }
 
0
karanrajkkr953 weeks ago
int maxLength(string S){       stack<int>st;       st.push(-1);       int count=0;       int n=S.size();       for(int i=0;i<n;i++){           if(S[i]=='('){               st.push(i);           }           else{               st.pop();               if(st.empty()){                   st.push(i);               }               else{                   int k=i-st.top();                   count=max(count,k);               }           }       }       return count;   }
+1
conceptcodcbue3 weeks ago
Detail Explanation and Java Code link: https://youtu.be/N7Flx0qA9Ro
Logic:1) when going from left to right, if ')' is more than '(', then it is an invalid case and restart count.2) when going from right to left '(' is more than ')', then it is an invalid case and restart count.Step 2 is needed because step 1 will give the wrong answer in this example, "(()"
 
+1
shubhamrikhari86514 weeks ago
int maxLength(string s){       int l = 0, r = 0, maxi = INT_MIN, maxi1 = INT_MIN;       bool x = false;       for(int i=0; i<s.size(); i++) {           if(s[i] == '(') {               l++;           }           else if(s[i] == ')') {               r++;           }           if(l==r) {               maxi = max(maxi, 2*l);               x = true;           }           else if(r > l) {               l = 0, r = 0;           }       }             l = 0, r = 0;       for(int i=s.size()-1; i>=0; i--) {           if(s[i] == '(') {               l++;           }           else if(s[i] == ')') {               r++;           }           if(l == r) {               maxi1 = max(maxi1, 2*l);               x = true;           }           else if(l > r) {               l = 0, r = 0;           }       }       if(x == true)           return max(maxi,maxi1);       return 0;   }
0
hridayguna4 weeks ago
Easy java soln || 0.2sec
 
static int maxLength(String s){       int len = 0;       int[] dp = new int[s.length()+1];       Stack<Integer> stack = new Stack<>();       for(int i=0;i<s.length();i++){           if(s.charAt(i)=='('){               dp[i]=0;               stack.push(i);           }else if(s.charAt(i)==')'){               if(stack.isEmpty()){                   dp[i] = 0;               }else{                   int j = stack.pop();                   if(j>0){                   dp[i] = dp[i-1]+dp[j-1]+2;}                   else{                       dp[i] = dp[i-1]+2;                   }               }           }           len = Math.max(dp[i],len);       }       return len;   }
0
anis231 month ago
C++ Solution || Stack || Short & Simple:
 

class Solution{
public:
    int maxLength(string S){
        // code here
        int n = S.length();
        stack<int> st;
        st.push(-1);
        int m = 0;
        for (int i = 0; i < n; i++)
        {
            int p = st.size();
            if (S[i] == '(')
            {
                st.push(i);
            }
            else
            {
                st.pop();
                if (st.empty())
                {
                    st.push(i);
                }
                else
                {
                    int k = i - st.top();
                    m = max(m, k);
                }
            }
        }
        return m;
    }
};
0
mondaltarakes1 month ago
 int maxLength(string S){
        // code here
       stack<int>st;
       int prev[S.length()];
       for(int i=0;i<S.length();i++)
       prev[i]=0;
       int i=0,count=0,maxcount=0;
      
      while(i<S.length()){
           if(!st.empty()  && S[st.top()]=='('  && S[i]==')'){
               prev[st.top()]=1;
               prev[i]=1;
               st.pop();
               i++;
           }else{
           st.push(i);
           i++;
           }
       }
  
  //find maximum consecutive 1's
       for(int i=0;i<S.length();i++){
          if(prev[i]==0){
             count=0;
          }else{
          count++;
           maxcount=max(maxcount,count);
         
          }
       }
    
        maxcount=max(maxcount,count);
        
       return maxcount;
    }

    
0
kumaarsahab4321 month ago
//Using Stack
int maxLength(string S){
        stack<int> s;
        s.push(-1) ;
        int len=0, n=S.length() ;
        for(int i=0 ; i<n ; i++)
        {
            if(S[i]=='(') s.push(i) ;
            if(S[i]==')'){
                s.pop() ;
                if(s.empty()) s.push(i) ;
                else{
                    int temp=i-s.top() ;
                    len=max(temp,len) ;
                }
            }
        }
        
        return len ;
    }
0
ashwinkumar99311 month ago
Simple C++ understandable solution
int maxLength(string S){
        // code here
        
        int n = S.length();
        
        stack<pair<int, char>> stk;
        
        stk.push({0, 'B'});  // for base condn
        
        for(int i=0;i<n;i++){
            
            char ch = S[i];
            
            int x = stk.top().first;
            char t = stk.top().second;
            
            if(t=='(' && ch==')'){ 
                stk.pop();
                int x2 = stk.top().first;
                char t2 = stk.top().second;
                stk.pop();
                // insert sum of previous sequences in stack
                stk.push({x+1+x2, t2});
            }
            else{
                stk.push({0, ch}); // insert '0' since rule is breaked;
            }
        }
        
        int ans = 0;
        
        while(!stk.empty()){
            int k = stk.top().first;
            
            ans = max(ans, k);
            
            stk.pop();
        }
        
        return ans*2;
    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested 
                                    against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
                                    On submission, your code is tested against multiple test cases consisting of all
                                        possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
                                        the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the 
                                correctness of code. On submission, your code is tested against multiple test cases
                                    consisting of all possible corner cases and stress constraints.