Copied to Clipboard
Longest valid Parentheses
Hard Accuracy: 48.35% Submissions: 14474 Points: 8

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|)

1 ≤ |S| ≤ 105  

We are replacing the old Disqus forum with the new Discussions section given below.
Click here to view old Disqus comments.

to report an issue on this page.


We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?


All Submissions

My Submissions:

Login to access your submissions.

Longest valid Parentheses

Output Window