You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
For a given expression in the form of a string, find if there exist any redundant brackets or not. It is given that the expression contains only rounded brackets or parenthesis and the input expression will always be balanced.
3
+
A pair of the bracket is said to be redundant when a sub-expression is surrounded by unnecessary or needless brackets.
4
+
Example:
5
+
Expression: (a+b)+c
6
+
Since there are no needless brackets, hence, the output must be 'false'.
7
+
Expression: ((a+b))
8
+
The expression can be reduced to (a+b). Hence the expression has redundant brackets and the output will be 'true'.
9
+
Input Format :
10
+
The first and the only line of input contains a string expression, without any spaces in between.
11
+
Output Format :
12
+
The first and the only line of output will print either 'true' or 'false'(without the quotes) denoting whether the input expression contains redundant brackets or not.
13
+
Constraints:
14
+
0 <= N <= 10^6
15
+
Where N is the length of the expression.
16
+
Time Limit: 1 second
17
+
Sample Input 1:
18
+
a+(b)+c
19
+
Sample Output 1:
20
+
true
21
+
Explanation:
22
+
The expression can be reduced to a+b+c. Hence, the brackets are redundant.
23
+
Sample Input 2:
24
+
(a+b)
25
+
Sample Output 2:
26
+
false"""
27
+
28
+
defcheckRedundantBrackets(expression) :
29
+
s=expression
30
+
le=len(s)
31
+
l=[]
32
+
foriinrange(le):
33
+
ifs[i]=="(": # checks open bracket
34
+
l.append("(") # put open brackets to stack
35
+
elifs[i] in"+-*/": #check char in the string
36
+
l.append(s[i]) #if it an operator then put it into the stack
37
+
elifs[i] ==")": # checks close bracket
38
+
ifl[-1]=="(": # and if there is no operator in the stack
39
+
returnTrue# then its redundant and further code will not run
40
+
elifl[-1] in"+-*/": # if it has operator
41
+
42
+
whilel[-1]!="(": # then pop till we don't get open bracket
43
+
l.pop()
44
+
l.pop() #pop open bracket
45
+
returnFalse#it is false if no redundant bracket is found till end
0 commit comments