Stacks and Queues Infix, prefix and postfix
209. Postfix to Prefix
You are given a valid arithmetic expression expression in postfix notation, where each operator comes
right after its two operands. Return the same expression in prefix notation, where each operator comes
right before its two operands. For example, ab+ becomes +ab.
Every operand is a single character, a lowercase letter or a digit. The operators are +, -, *, / and
^ (power), and each one takes two operands. In both notations the left operand comes before the right one,
so ab- means a-b, and its prefix form is -ab. Neither notation needs brackets, and the input has no
spaces.
Answers are shown in double quotes.
Example 1
Input: expression = "ab-c*de+/"
"/*-abc+de"Explanation: The expression is ((a-b)*c)/(d+e). Its last operator, /, comes first in prefix. Then come its left
operand, *-abc, and its right operand, +de.
Example 2
Input: expression = "4x2^*"
"*4^x2"Explanation: x2^ is the right operand of *, so the expression is 4*(x^2). In prefix the * comes first, then
4, then ^x2.
Example 3
Input: expression = "q"
"q"Explanation: A single operand is a complete expression, and it reads the same in both notations.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ expression.length ≤ 3 × 105expressionholds lowercase letters, digits and the operators+ - * / ^- Every operand is a single letter or digit, and every operator has two operands
expressionis a valid postfix expression
Clarifying questions
What you would ask an interviewer before writing any code.