Skip to content

Commit a445b14

Browse files
authored
Add files via upload
1 parent daa6984 commit a445b14

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
"""Check redundant brackets
2+
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+
def checkRedundantBrackets(expression) :
29+
s=expression
30+
le = len(s)
31+
l=[]
32+
for i in range(le):
33+
if s[i]=="(": # checks open bracket
34+
l.append("(") # put open brackets to stack
35+
elif s[i] in "+-*/": #check char in the string
36+
l.append(s[i]) #if it an operator then put it into the stack
37+
elif s[i] ==")": # checks close bracket
38+
if l[-1]=="(": # and if there is no operator in the stack
39+
return True # then its redundant and further code will not run
40+
elif l[-1] in "+-*/": # if it has operator
41+
42+
while l[-1]!="(": # then pop till we don't get open bracket
43+
l.pop()
44+
l.pop() #pop open bracket
45+
return False #it is false if no redundant bracket is found till end
46+
47+
expression=input("Enter the expression:\n")
48+
print("output:")
49+
if checkRedundantBrackets(expression):
50+
print('true')
51+
else:
52+
print('false')
53+
"""
54+
Time complexity: O(n)
55+
Space complexity: O(n)
56+
"""

0 commit comments

Comments
 (0)