Stacks and Queues Infix, prefix and postfix
205. Infix to Prefix
You are given an arithmetic expression in ordinary infix notation, as a string expression. Return the
same expression in prefix notation.
Every operand is a single character, a lowercase letter or a digit. The operators are +, -, *, / and
^, and each one takes two operands. ^ binds tightest, then * and /, then + and -. Brackets can
change the grouping. Operators of the same level group from the left, so a-b-c means (a-b)-c, except
^, which groups from the right, so a^b^c means a^(b^c).
In prefix notation every operator comes before its two operands, the left one first. So a-b becomes
-ab, and (a-b)*c becomes *-abc. Prefix needs no brackets, because the order of the characters fixes
the grouping.
Answers are shown in double quotes.
Example 1
Input: expression = "p-q-r*(s+t)"
"--pq*r+st"Explanation: The minus signs group from the left, so this is (p-q)-(r*(s+t)). The second minus runs last, so it
comes first, followed by -pq and then *r+st.
Example 2
Input: expression = "2^3^k"
"^2^3k"Explanation: ^ groups from the right, so this is 2^(3^k). The first ^ runs last, and its right operand is
^3k.
Example 3
Input: expression = "((m))"
"m"Explanation: A single operand needs no operator, so the brackets go and only m is left.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ expression.length ≤ 105expressionholds only lowercase letters, digits,+,-,*,/,^,(and), with no spaces.expressionis a valid infix expression: every operator has an operand on each side, and every bracket pair is matched and holds an expression.
Clarifying questions
What you would ask an interviewer before writing any code.