Skip to content

Longest Valid Parentheses

Leetcode 32. Longest Valid Parentheses

Leetcode 32. Longest Valid Parentheses

Problem

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

Example 1:

Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".

Example 2:

Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".

Example 3:

Input: s = ""
Output: 0

Constraints:

  • 0 <= s.length <= 3 * 104
  • s[i] is '(', or ')'.

Source : Leetcode 32. Longest Valid Parentheses

Solution

We can calculate number of left brackets and right brackets from the beginning and when left = right, we can take the length of valid parentheses and update our answer.

Consider the test cases :

a. Case-1: ( ( ( ) ) )

In this case when we are at the 3rd left bracket, left = 3 and right = 0. When we reach at the end we get left = 3 and right = 3. So, the max length will be 2 * left or right = 6.

b. Case-2: ( ( ( ) )

In this case, at the end of the string we get left = 3 and right = 2. So, we never get left and right equal. To handle this kind of situation, we can traverse from last of the string as well. If we traverse from last, we will get right = 2 and left = 2 when we are at index = 1. Thus we will get the answer 4 (2 * left or right).

The Algorithm

Initialize left = right = 0.

Start from beginning and count left and right as you go. If at any point left = right, get length and update answer. If at any point right > left, reinitialize left = right = 0.

Re-Initialize left = right = 0.

Start from end and count left and right as you go. If at any point left = right, get length and update answer. If at any point left > right, reinitialize left = right = 0.

C++ Code
class Solution {
public:
    int longestValidParentheses(string s) {
        int left = 0;
        int right = 0;
        int ans = 0;
        int len = s.size();
        
        for(int i = 0; i < len; i++){
            if(s[i] == '(')
                left++;
            else
                right++;
            
            if(left == right)
                ans = max(ans, 2 * left);
            else if(right >= left)
                left = right = 0;
        }
        left = right = 0;
        for(int i = len - 1; i >= 0; i--){
            if(s[i] == '(')
                left++;
            else
                right++;
            
            if(left == right)
                ans = max(ans, 2 * left);
            else if(left >= right)
                left = right = 0;
        }
        return ans;
    }
};
Conclusion

If you like this post or hate it, please write your opinion in the comment section. For more posts like this, please check below or go to the home page.

Happy Coding! 🙂

45 thoughts on “Longest Valid Parentheses”

  1. Your article gave me a lot of inspiration, I hope you can explain your point of view in more detail, because I have some doubts, thank you.

  2. Your article gave me a lot of inspiration, I hope you can explain your point of view in more detail, because I have some doubts, thank you.

  3. Apoiar ferramentas de apostas e estar equipado com uma plataforma diversificada de transações financeiras, a 20Bet oferece suporte tangível aos jogadores. Este é um lugar onde eles podem apostar com dinheiro real, respaldados por concorrentes de diversas disciplinas esportivas. 20bet

  4. Hi my family member! I want to say that this post is awesome, nice written and come with approximately all significant infos. I would like to peer extra posts like this.

  5. Hi i think that i saw you visited my web site thus i came to Return the favore I am attempting to find things to improve my web siteI suppose its ok to use some of your ideas

  6. Hello, i think that i saw you visited my weblog so i came to ?eturn the favor텶’m trying to find things to improve my web site!I suppose its ok to use some of your ideas!!

  7. To the foolishhungry.com webmaster, Your posts are always well received by the community.

  8. Dear foolishhungry.com owner, Your posts are always well-supported by research and data.

  9. It was impossible for me to leave your website without expressing my gratitude for the excellent knowledge you give your visitors. Without a doubt, I’ll be checking back frequently to see what updates you’ve made.

  10. Hi, great post There is a problem with your website on Internet Explorer. Despite being the most popular browser, many people will not be able to view your excellent work because of this issue.

  11. Hello i think that i saw you visited my weblog so i came to Return the favore Im trying to find things to improve my web siteI suppose its ok to use some of your ideas

  12. Simply desire to say your article is as surprising The clearness in your post is simply excellent and i could assume you are an expert on this subject Fine with your permission let me to grab your feed to keep up to date with forthcoming post Thanks a million and please carry on the gratifying work

Leave a Reply

Your email address will not be published. Required fields are marked *