Amazon | Onsite | Postfix to Infix with minimal parantheses
Company: Amazon
Role: sde i, sde ii
Interview Stage: Onsite
Location: unknown
Year: unknown
Original Post Content:
Problem Statement: Convert the given postfix expression to the corresponding infix expression while minimising the use of parantheses.
Example 1:
Input -> abc+*
Output -> a*(b+c)
Example 2:
Input -> abc*+
Output -> a+b*c
Constraint: Operators limited to addition (+) and multiplication (*).
Approach: A minor tweak on the postfix to infix problem. Utilised two stacks, one for operands and one for the corresponding operators. While popping the operands (simple or compound) from the operand stack, the corresponding operators were also popped to compare their precedence with the current operator. Operands were paranthesised accordingly.
Extension: The operator constraint was removed to allow subtraction, division and exponential operations.
Example:
Input -> abc--
Output -> a-(b-c)
Compared to example 2 of the original problem, one can observe how parantheses insertions can change based on the operator.
Approach: Introduced the concept of associativity to the code to manage this. During the popping and precedence comparison of the operators, the associativity of the current operator was also considered to figure out whether/where to insert a paranthesis.