Stacks and Queues Infix, prefix and postfix
206. Postfix to Infix
You are given an arithmetic expression in postfix notation as a string expression. Return the same
expression in infix notation, fully parenthesised.
Each operand is a single character, a lowercase letter or a digit. The operators are +, -, *, / and
^, and each one takes two operands. In postfix notation an operator comes right after its two operands,
and the earlier of the two is the left operand, so ab- means a − b. An operand can itself be an
expression: in abc*+, the + adds a and the result of bc*.
In the answer, every operator sits with its two operands inside one pair of parentheses, as in
((a-b)*c), and that includes the operator applied last. A single operand gets no parentheses. The answer
has no spaces.
Answers are shown in double quotes.
Example 1
Input: expression = "ab4^-c/"
"((a-(b^4))/c)"Explanation: The ^ works on b and 4, giving (b^4). The - then subtracts that from a, and the / divides
the result by c.
Example 2
Input: expression = "931--"
"(9-(3-1))"Explanation: The first - works on 3 and 1. The second - takes 9 as its left operand and (3-1) as its
right one.
Example 3
Input: expression = "k"
"k"Explanation: A single operand is already a whole expression, so it gets no parentheses.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ expression.length ≤ 3 × 105- Each character of
expressionis a lowercase letter, a digit, or one of+ - * / ^ expressionis a valid postfix expression
Clarifying questions
What you would ask an interviewer before writing any code.