Problem of the day
You are given the expression ‘expr’ with parenthesis. Your task is to find if the given expression contains duplicate parenthesis. A set of parenthesis is duplicate if multiple parenthesis surrounds the same subexpression.
For Example:You are given ‘expr’ = “(a+b)+((c+d))”, here the subexpression “c+d” is surrounded by two parentheses. Hence the expression contains duplicate parenthesis. Hence the answer is “YES”.
The first line of input contains a single integer ‘T’, representing the number of test cases.
The first line of each test case contains a string, ‘expr’, representing the given expression.
Output Format:
For each test case, print “YES” if the expression contains a duplicate parenthesis. Otherwise, print “NO”.
Print a single line for each test case.
1 <= T <= 10
1 <= |expr| <= 10^6
Time Limit: 1 sec
Note:
You do not need to print anything. It has already been taken care of. Just implement the function.
2
(a+b)+((c+d))
((a+b) + c)
YES
NO
For the first test case, ‘expr’ = “(a+b)+((c+d))”, here, the subexpression “c+d” is surrounded by two parentheses. Hence the expression contains duplicate parenthesis. Hence the answer is “YES”.
For the second test case, ‘expr’ = “((a+b) + c)”, here, no subexpression is surrounded by multiple parentheses. Hence the answer is “NO”.
2
(a+b)+((c+d))
((a+b)+(c+d))
YES
NO
Try to use the stack.
In this approach, we will use the stack data structure and iterate through every character in the expression of the character is not a closed parenthesis ( ( ) then, we push it to the top of the stack. Otherwise, if a closing parenthesis is found we pop the stack until a ‘(‘ is found. If the number of characters between the parenthesis is not greater than 1 then return false. Otherwise, return true.
Algorithm:
O(N), Where N is the length of the expression.
We are iterating over the expression once, which will cost O(N) time. Hence the overall time complexity is O(N).
O(N), Where N is the length of the expression.
We are maintaining a stack that will have N elements in the worst case and will cost O(N) space. Hence the overall space complexity is O(N).