49. Stack-2: pre,in,post-fix
Priority order of operators: (^) > ( *, / ) > (+, -)
----------------------------------------------------------------------------------------------------------------------------
2. infix to prefix is modified infix to postfix, since u just reverse string & replace brackets & do postfix conversion with some conditions & reverse the postfix answer
3. for other conversions:⭐⭐
we try to traverse from that side where we find 2 operands before an operator
-----------------------------------------------------------------------------------------------------------------------------
time: O(2n), space: O(2n)
we need- 1. (variable i)
2. (stack st)
3. (variable ans)
1. iterate through infix expression
2. if u see an operand, insert it into ans
3. if u see an operator & stack == empty, then push it into a stack
4. if u see an operator & stack != empty, then :
if curr priority > st.top() => push curr into stack
if curr priority <= st.top() => pop out from stack and add to ans, repeat till u hit above cond
5. if u encounter ( push it
6. if u encounter ) remove everything from stack & add to ans till u get ( and also remove ( then again pop & add to ans
1. reverse given string & make ( to ) & ) to (
2. do infix to postfix conversion
3. reverse the answer
change: if, curr priority < st.top() => only then do pop out of stack & add to ans till curr >= st.top
here, curr can be any operator except ^
---------------------------------------------------------------------------------------------------------------------------
time: O(n), space: O(n)
1. iterate from left to right
2. store operands into a stack
3. if u encounter an operator- pick last 2 elements from stack--> put operator in b/w them--> wrap in brackets-->push back this shit into stack
(2nd top # 1st top), where # is operator
when iteration is over, stack only contains 1 element which is my answer
time: O(n), space:O(n)
iterate from right to left
this time store as, ( 1st top # 2nd top )
1. push operands into stack
2. if u see operator, do ( # top2 top1 ) into stack after popping out top2 and top1
1. start from back
2. if operand, push into stack
3. if operator, pop out last 2 top elements, do ( top1 top2 # )
Comments
Post a Comment