oneby7

Stacks and Queues Infix, prefix and postfix

208. Prefix to Postfix

Medium

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"

Output: "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"

Output: "z"

Explanation: A single operand is a complete expression, and it reads the same in both notations.

Example 3

Input: expression = "/9-x1"

Output: "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.

expression = "-a*bc"

Constraints

  • 1 ≤ expression.length ≤ 3 × 105
  • expression holds only lowercase letters, digits and the operators +, -, *, / and ^.
  • expression is a valid prefix expression.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.