Given a string expression that holds a valid postfix (Reverse Polish) expression, convert it to infix notation with the minimum number of parentheses needed to preserve the correct order of operations.
Operands are single lowercase letters (a-z) or digits (0-9). Operators are +, -, * and /.
* and / have higher precedence than + and -. Operators of equal precedence are left-associative. Only add parentheses where removing them would change the evaluation result.
Function Signature
def postfix_to_infix(expression: str) -> str:
...
Rules
-
Each character of
expression
is one operand or one operator. The input and the output contain no spaces.
-
The output contains the same operands and operators in the same left-to-right order as the expression they encode. Only the placement of parentheses is up to you.
-
Evaluation uses exact arithmetic with no integer truncation, so
a*(b/c)
and
a*b/c
have the same value and the shorter form is expected.
-
A single operand converts to itself.
Constraints
-
1 <= expression.length <= 500
-
Operands are single lowercase letters (
a
-
z
) or digits (
0
-
9
).
-
Operators are one of
+
,
-
,
*
,
/
.
-
The input is a valid postfix expression.
Examples
Input: expression = "ab+cd-*"
Output: "(a+b)*(c-d)"
The postfix means (a+b)*(c-d). Both groups need parentheses because + and - have lower precedence than the * that combines them. Without them, a+b*c-d would multiply b by c.
Input: expression = "abc*+de/-"
Output: "a+b*c-d/e"
The postfix means (a+(b*c))-(d/e). b*c and d/e bind tighter than the + and - around them, so they need no parentheses. The left operand of - is a+b*c, and because + and - have equal precedence and group left to right, a+b*c-d/e already computes it first.
Input: expression = "abc-+de+-"
Output: "a+b-c-(d+e)"
The postfix means (a+(b-c))-(d+e). a+(b-c) can be written a+b-c because (a+b)-c has the same value. The parentheses around d+e must stay: without them the string would subtract d and then add e.