We are given a string having parenthesis like below
“( ((X)) (((Y))) )”
We need to find the maximum depth of balanced parenthesis, like 4 in above example. Since ‘Y’ is surrounded by 4 balanced parenthesis.
If parenthesis are unbalanced then return -1.
Input : S = "( a(b) (c) (d(e(f)g)h) I (j(k)l)m)"; Output : 4 Input : S = "( p((q)) ((s)t) )"; Output : 3 Input : S = ""; Output : 0 Input : S = "b) (c) ()"; Output : -1 Input : S = "(b) ((c) ()" Output : -1
Method 1 (Uses Stack)
A simple solution is to use a stack that keeps track of current open brackets.
1) Create a stack. 2) Traverse the string, do following for every character a) If current character is ‘(’ push it to the stack . b) If character is ‘)’, pop an element. c) Maintain maximum count during the traversal.
Time Complexity : O(n)
Auxiliary Space : O(n)
Method 2 ( O(1) auxiliary space )
This can also be done without using stack.
1) Take two variables max and current_max, initialize both of them as 0. 2) Traverse the string, do following for every character a) If current character is ‘(’, increment current_max and update max value if required. b) If character is ‘)’. Check if current_max is positive or not (this condition ensure that parenthesis are balanced). If positive that means we previously had a ‘(’ character so decrement current_max without worry. If not positive then the parenthesis are not balanced. Thus return -1. 3) If current_max is not 0, then return -1 to ensure that the parenthesis are balanced. Else return max
Below is the implementation of above algorithm.
Time Complexity : O(n)
Auxiliary Space : O(1)
This article is contributed by Gaurav Sharma. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Find if an expression has duplicate parenthesis or not
- Find the first maximum length even word from a string
- Number of balanced parenthesis substrings
- Check for balanced parenthesis without using stack
- Identify and mark unmatched parenthesis in an expression
- Find the longest sub-string which is prefix, suffix and also present inside the string
- Find length of longest subsequence of one string which is substring of another string
- Find the character in first string that is present at minimum index in second string
- Given a string and an integer k, find the kth sub-string when all the sub-strings are sorted according to the given condition
- Find the count of palindromic sub-string of a string in its sorted form
- Find the smallest window in a string containing all characters of another string
- Queries to find the last non-repeating character in the sub-string of a given string
- Queries to find the first non-repeating character in the sub-string of a string
- Find a palindromic string B such that given String A is a subsequense of B
- Find if a string starts and ends with another given string