Stacks and Queues Infix, prefix and postfix
208. Prefix to Postfix
You are given a string expression that holds an arithmetic expression in prefix notation. Return the
same expression in postfix notation.
Each operand is a single character, a lowercase letter or a digit, so 12 is two operands. The operators are
+, -, *, / and ^, and each one takes exactly two operands.
In prefix notation an operator comes before its two operands, and in postfix notation it comes after them.
An operand can be a single character or a whole smaller expression. So +ab in prefix is ab+ in postfix,
and both mean a + b. Neither notation needs brackets, so every expression has exactly one postfix form.
Answers are shown in double quotes.
Example 1
Input: expression = "-*ab+c/de"
"ab*cde/+-"Explanation: In ordinary notation this is (a × b) − (c + d / e). The two operands of the minus are *ab and
+c/de, which become ab* and cde/+ in postfix. The minus goes after both.
Example 2
Input: expression = "z"
"z"Explanation: A single operand is a complete expression, and it reads the same in both notations.
Example 3
Input: expression = "/9-x1"
"9x1-/"Explanation: This is 9 / (x − 1). The digits are operands like the letters, and the right operand of the division is
the whole of -x1.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ expression.length ≤ 3 × 105expressionholds only lowercase letters, digits and the operators+,-,*,/and^.expressionis a valid prefix expression.
Clarifying questions
What you would ask an interviewer before writing any code.