oneby7

Stacks and Queues Infix, prefix and postfix

204. Infix to Postfix

Medium

You are given a valid arithmetic expression expression in ordinary infix notation, where each operator sits between its two operands. Return the same expression in postfix notation, where each operator comes right after its two operands. For example, a+b becomes ab+.

Every operand is a single character, a lowercase letter or a digit. The operators are +, -, *, / and ^ (power), and the expression may use the brackets ( and ). There are no spaces.

The usual rules decide which operands each operator takes. Brackets come first. Then ^ binds tightest, then * and /, then + and -. Operators of the same precedence group from the left, so a-b-c means (a-b)-c. The one exception is ^, which groups from the right, so a^b^c means a^(b^c). Under these rules every expression has exactly one postfix form, and it needs no brackets: a*(b+c) becomes abc+*.

Answers are shown in double quotes.

Example 1

Input: expression = "a-b*(c+d)-e"

Output: "abcd+*-e-"

Explanation: The brackets put c+d first. Then b is multiplied by that sum, and a minus the product is calculated. The last minus comes last, because two minuses group from the left.

Example 2

Input: expression = "2^3^2*k"

Output: "232^^k*"

Explanation: ^ groups from the right, so 3^2 is calculated first and 2 is raised to it. The product with k comes last, because * binds less tightly than ^.

Example 3

Input: expression = "((m))"

Output: "m"

Explanation: Brackets around a single operand change nothing, and postfix has no brackets.

Check your understanding

Work out the answer for this input before you write any code.

expression = "a+b*c-d"

Constraints

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