Given a balanced expression that can contain opening and closing parenthesis, check if it contains any duplicate parenthesis or not.

For example,

Input:  ((x+y))+z
Output: true
Explanation: Duplicate () found in subexpression ((x+y))
 
 
Input:  (x+y)
Output: false
Explanation: No duplicate () is found
 
 
Input:  ((x+y)+((z)))
Output: true
Explanation: Duplicate () found in subexpression ((z))

Practice this problem

We can use a stack to solve this problem. The idea is to traverse the given expression and

  • If the current character in the expression is not a closing parenthesis ')', push the character into the stack.
  • If the current character in the expression is a closing parenthesis ')', check if the topmost element in the stack is an opening parenthesis or not. If it is an opening parenthesis, then the subexpression ending at the current character is of the form ((exp)); otherwise, continue popping characters from the stack till matching '(' is found for current ')'.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

The expression has duplicate parenthesis

Java


Download  Run Code

Output:

The expression has duplicate parenthesis

Python


Download  Run Code

Output:

The expression has duplicate parenthesis

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the length of the input expression.

 
Suggested Read:

Find all strings of a given length containing balanced parentheses

Find all combinations of non-overlapping substrings of a string