oneby7

Stacks and Queues Infix, prefix and postfix

207. Prefix to Infix

Medium

You are given an arithmetic expression in prefix 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 prefix notation an operator comes right before its two operands, and the first of the two is the left operand, so -ab means a − b. An operand can itself be an expression: in +a*bc, 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 = "-*ab/cd"

Output: "((a*b)-(c/d))"

Explanation: The - comes first, so it is applied last. Its left operand is *ab, which gives (a*b), and its right operand is /cd, which gives (c/d).

Example 2

Input: expression = "+a*-bc4"

Output: "(a+((b-c)*4))"

Explanation: The + takes a as its left operand and everything after it, *-bc4, as its right one. Inside that, the * takes -bc and 4.

Example 3

Input: expression = "q"

Output: "q"

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 = "-a*bc"

Constraints

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