oneby7

Stacks and Queues Infix, prefix and postfix

205. Infix to Prefix

Medium

You are given an arithmetic expression in ordinary infix notation, as a string expression. Return the same expression in prefix notation.

Every operand is a single character, a lowercase letter or a digit. The operators are +, -, *, / and ^, and each one takes two operands. ^ binds tightest, then * and /, then + and -. Brackets can change the grouping. Operators of the same level group from the left, so a-b-c means (a-b)-c, except ^, which groups from the right, so a^b^c means a^(b^c).

In prefix notation every operator comes before its two operands, the left one first. So a-b becomes -ab, and (a-b)*c becomes *-abc. Prefix needs no brackets, because the order of the characters fixes the grouping.

Answers are shown in double quotes.

Example 1

Input: expression = "p-q-r*(s+t)"

Output: "--pq*r+st"

Explanation: The minus signs group from the left, so this is (p-q)-(r*(s+t)). The second minus runs last, so it comes first, followed by -pq and then *r+st.

Example 2

Input: expression = "2^3^k"

Output: "^2^3k"

Explanation: ^ groups from the right, so this is 2^(3^k). The first ^ runs last, and its right operand is ^3k.

Example 3

Input: expression = "((m))"

Output: "m"

Explanation: A single operand needs no operator, so the brackets go and only m is left.

Check your understanding

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

expression = "a-b-c"

Constraints

  • 1 ≤ expression.length ≤ 105
  • expression holds only lowercase letters, digits, +, -, *, /, ^, ( and ), with no spaces.
  • expression is a valid infix expression: every operator has an operand on each side, and every bracket pair is matched and holds an 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.