Stacks and Queues Infix, prefix and postfix
207. Prefix to Infix
You are given an arithmetic expression in prefix 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 prefix notation an operator comes right before its two operands,
and the first of the two is the left operand, so -ab means a − b. An operand can itself be an expression:
in +a*bc, 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 = "-*ab/cd"
"((a*b)-(c/d))"Explanation: The - comes first, so it is applied last. Its left operand is *ab, which gives (a*b), and its
right operand is /cd, which gives (c/d).
Example 2
Input: expression = "+a*-bc4"
"(a+((b-c)*4))"Explanation: The + takes a as its left operand and everything after it, *-bc4, as its right one. Inside that,
the * takes -bc and 4.
Example 3
Input: expression = "q"
"q"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 prefix expression
Clarifying questions
What you would ask an interviewer before writing any code.