Given a string consisting of opening and closing parenthesis, find the length of the longest balanced parenthesis in it.

For example, the longest balanced parenthesis is highlighted in the following expressions:


((()()
(()())(()
(((()
((((
()()

Practice this problem

 
A simple solution would be to generate all substrings of the given string and, for each substring, check if it is balanced or not. If the substring is balanced and has more length than the maximum length balanced substring found so far, update the result. The time complexity of this solution is O(n3) since there are O(n2) substrings for a string of length n, and each substring takes O(n) time to check if it is balanced.

 
We can solve this problem in O(n) time by using O(n) space. The idea is to iterate over the string characters, and if the current character is an opening parenthesis, push its index in a stack. If the current character is a closing parenthesis, pop the top index from the stack and push the current index into the stack if it becomes empty.

We can get the length of the longest balanced parenthesis ending at the current character (closing parenthesis) by finding the difference between the current index and index at the stack’s top. We keep track of the length of the longest balanced parenthesis and update it whenever required.

 
For example, the following table demonstrates the above operations for string (()())((). Note that the stack initially contains -1 to handle the case when balanced parenthesis starts from index 0.

Longest Balanced Parenthesis

 
The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code