Stacks and Queues Infix, prefix and postfix
204. Infix to Postfix
You are given a valid arithmetic expression expression in ordinary infix notation, where each operator
sits between its two operands. Return the same expression in postfix notation, where each operator comes
right after its two operands. For example, a+b becomes ab+.
Every operand is a single character, a lowercase letter or a digit. The operators are +, -, *, / and
^ (power), and the expression may use the brackets ( and ). There are no spaces.
The usual rules decide which operands each operator takes. Brackets come first. Then ^ binds tightest, then
* and /, then + and -. Operators of the same precedence group from the left, so a-b-c means
(a-b)-c. The one exception is ^, which groups from the right, so a^b^c means a^(b^c). Under these
rules every expression has exactly one postfix form, and it needs no brackets: a*(b+c) becomes abc+*.
Answers are shown in double quotes.
Example 1
Input: expression = "a-b*(c+d)-e"
"abcd+*-e-"Explanation: The brackets put c+d first. Then b is multiplied by that sum, and a minus the product is calculated.
The last minus comes last, because two minuses group from the left.
Example 2
Input: expression = "2^3^2*k"
"232^^k*"Explanation: ^ groups from the right, so 3^2 is calculated first and 2 is raised to it. The product with k comes
last, because * binds less tightly than ^.
Example 3
Input: expression = "((m))"
"m"Explanation: Brackets around a single operand change nothing, and postfix has no brackets.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ expression.length ≤ 105expressionholds lowercase letters, digits, the operators+ - * / ^and the brackets(and)- Every operand is a single letter or digit, and every operator has two operands
expressionis a valid infix expression
Clarifying questions
What you would ask an interviewer before writing any code.