Be the first user to complete this post

  • 0
Add to List

361. Convert Prefix to Infix Expression

Objective: Given a Prefix expression, write an algorithm to convert it into Infix expression.


Input: Prefix expression: + A B
Output: Infix expression- (A + B)

Input: Prefix expression: *-A/BC-/AKL
Output: Infix expression: ((A-(B/C))*((A/K)-L))

Approach: Use Stacks


Iterate the given expression from right to left (in reverse order), one character at a time

  1. If character is operand, push it to stack.
  2. If character is operator,
    1. pop operand from stack, say it’s s1.
    2. pop operand from stack, say it’s s2.
    3. perform (s1 operator s2) and push it to stack.
  3. Once the expression iteration is completed, initialize result string and pop out from stack and add it to result.
  4. Return the result.

Please walk through the example below for more understanding.


Prefix Expression: *-A/BC-/AKL
Infix Expression: ((A-(B/C))*((A/K)-L))