Microsoft Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
the priority of operators is "++" > "* /" > "+ -" > "( or ) or boundary of the string"
So for expression like "opA(...op1...opN...)opB", if the priority of Min{op1....opN} is >= Max{opA, opB}, then the () can be removed.
Firstly, remove redundant brackets like ((....))
Secondly, process the () from outter to inner (when processing the outter "()" ingore the operators inside the inner "()")
Little cowboy coding but it should work. The idea is to go recursive and solve each bracket seprately. Follow the BODMAS rule and set priorities (except 'B' has a -ve priority because w want to remove that.
expression = "(a+(b*c))*(d*(f*j))"
operations = {'*':2,'+':1,'(':-1,')':-1}
operators = ['*','+']
bracket_stack = []
brackets = ['(',')']
def remove_brackets(expr,start_location,total_length,left_operator,bracket_stack):
i = start_location+1
is_bracket_removable = True
while expr[i] != ')':
element = expr[i]
if element == '(':
i = remove_brackets(expr,i,total_length,operations[expr[i-1]],bracket_stack)
else:
if element in operators and is_bracket_removable:
if left_operator > operations[element]:
is_bracket_removable = False
i+=1
if is_bracket_removable and i+1 < total_length and operations[expr[i+1]] > left_operator:
is_bracket_removable = False
if is_bracket_removable:
expr[start_location] = ''
expr[i] = ''
return i
i=0
expr = list(expression)
while i<len(expr):
c = expr[i]
if c == '(':
i = remove_brackets(expr,i,len(expr),-1 if i==0 else operations[expr[i-1]],bracket_stack)
i+=1
print ''.join([c for c in expr if c!=''])
If an expression that has brackets results in the same postfix expression as the one without any brackets. Then all the brackets can be removed.
Algorithm - assuming that brackets are legally placed
1) Compute the postfix expression of the given expression (say STR) with brackets, lets call this postFix(STR) = orgPost
2) For each pair of bracket with STR
a) Remove the pair of bracket and compute STR'
b) if postFix(STR')=orgPost then STR=STR'
3) Return STR
Keep on pushing the operators into a stack and keep a track of the braces corresponding to the two pushed operators. If the operators are of unequal priority, let the braces remain, otherwise, remove them. Please correct me if I am wrong.
How about this:
- Varun April 11, 20131) Convert the expression to post fix notation
2) Convert the post fix notation back to infix