oneby7

Stacks and Queues Infix, prefix and postfix

206. Postfix to Infix

Medium

You are given an arithmetic expression in postfix notation as a string expression. Return the same expression in infix notation, fully parenthesised.

Each operand is a single character, a lowercase letter or a digit. The operators are +, -, *, / and ^, and each one takes two operands. In postfix notation an operator comes right after its two operands, and the earlier of the two is the left operand, so ab- means a − b. An operand can itself be an expression: in abc*+, the + adds a and the result of bc*.

In the answer, every operator sits with its two operands inside one pair of parentheses, as in ((a-b)*c), and that includes the operator applied last. A single operand gets no parentheses. The answer has no spaces.

Answers are shown in double quotes.

Example 1

Input: expression = "ab4^-c/"

Output: "((a-(b^4))/c)"

Explanation: The ^ works on b and 4, giving (b^4). The - then subtracts that from a, and the / divides the result by c.

Example 2

Input: expression = "931--"

Output: "(9-(3-1))"

Explanation: The first - works on 3 and 1. The second - takes 9 as its left operand and (3-1) as its right one.

Example 3

Input: expression = "k"

Output: "k"

Explanation: A single operand is already a whole expression, so it gets no parentheses.

Check your understanding

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

expression = "pq/r-"

Constraints

  • 1 ≤ expression.length ≤ 3 × 105
  • Each character of expression is a lowercase letter, a digit, or one of + - * / ^
  • 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.