oneby7

Stacks and Queues Infix, prefix and postfix

209. Postfix to Prefix

Medium

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+/"

Output: "/*-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^*"

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

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

expression = "abc-*"

Constraints

  • 1 ≤ expression.length ≤ 3 × 105
  • expression holds lowercase letters, digits and the operators + - * / ^
  • Every operand is a single letter or digit, and every operator has two operands
  • expression is a valid postfix 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.