VOOZH about

URL: https://www.geeksforgeeks.org/dsa/postfix-prefix-conversion/

⇱ Postfix to Prefix Conversion - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Postfix to Prefix Conversion

Last Updated : 14 Aug, 2025

Postfix: An expression is called the postfix expression if the operator appears in the expression after the operands. Simply of the form (operand1 operand2 operator). 
Example : AB+CD-* (Infix : (A+B) * (C-D) )

Prefix : An expression is called the prefix expression if the operator appears in the expression before the operands. Simply of the form (operator operand1 operand2). 
Example : *+AB-CD (Infix : (A+B) * (C-D) )

Problem Statement

Given a Postfix expression, convert it into a Prefix expression.

Instead of converting Postfix → Infix → Prefix, we can directly convert Postfix → Prefix.
This method is both efficient (fewer steps) and intuitive, since computers naturally evaluate expressions in Postfix form.

Examples:

Input : Postfix : AB+CD-*
Output : Prefix : *+AB-CD
Explanation : Postfix to Infix : (A+B) * (C-D)
Infix to Prefix : *+AB-CD

Input : Postfix : ABC/-AK/L-*
Output : Prefix : *-A/BC-/AKL
Explanation : Postfix to Infix : ((A-(B/C))*((A/K)-L))
Infix to Prefix : *-A/BC-/AKL

Algorithm for Postfix to Prefix:

We use a stack to build the prefix expression step by step:

  • Read the Postfix expression from left to right
  • If the symbol is an operand, then push it onto the Stack
  • If the symbol is an operator, then pop two operands from the Stack 
    Create a string by concatenating the two operands and the operator before them. 
    string = operator + operand2 + operand1
    And push the resultant string back to Stack
  • Repeat the above steps until end of Postfix expression.

 Below is the implementation of the above idea:


Output
Prefix : *-A/BC-/AKL

Time Complexity: O(N)
(We traverse the expression once, each operation is constant time.)
Auxiliary Space: O(N)
(Stack stores up to N elements in the worst case.)

Comment