Convert an Infix Expression to Postfix
Implement infixToPostfix
Given an infix expression
expr — operators appearing between their operands, the everyday way arithmetic is written, using single-character operands and standard operator precedence — convert it to postfix notationPostfix NotationAlso called Reverse Polish Notation: every operator follows its operands instead of sitting between them (e.g. "a+b" becomes "ab+"). It needs no parentheses and no precedence rules to evaluate — a single left-to-right stack pass suffices., where every operator comes immediately after its two operands instead of between them.
Postfix's appeal is that it can be evaluated with a single stack pass and no precedence rules at all — the conversion is where the precedence logic has to live instead. The classic technique (Shunting-Yard) handles that in one left-to-right pass: operands go straight to the output, and operators get held on a stack until something of equal-or-lower precedence needs to interrupt them, at which point they're released into the output in the right order. The same idea this category has used throughout — a stack remembers exactly what's still "pending" — applies here to remember exactly which operators are still waiting for their right-hand operand to finish being decided.
Example 1:
Input: expr = "p+q*r"
Output: "pqr*+"
Example 2:
Input: expr = "(m+n)*k"
Output: "mn+k*"
Example 3:
Input: expr = "x*y+z-w"
Output: "xy*z+w-"
+ 5 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ expr.length ≤ 15 - ●
expr contains only single-letter or single-digit operands, the operators '+', '-', '*', '/', '^', and matched parentheses - ●
'^' (exponentiation) is right-associative; all other operators are left-associative - ●
Standard precedence applies: '^' highest, then '*' and '/', then '+' and '-'
expr =
p+q*r