712305. Postfix to Prefix Conversion

Medium

Postfix to Prefix Conversion

Slug: postfix-to-prefix-conversion

Difficulty: Medium

Id: 712305

Topic Tags: None

Company Tags: None

Summary

Given a postfix expression, we need to convert it into its equivalent prefix form. This problem involves converting an expression from one notation (postfix) to another (prefix). The key concept involved here is the difference between these two notations and how they can be converted.

Detailed Explanation

A postfix expression is written in the order of operations (Last In First Out), whereas a prefix expression is written in the reverse order (First In Last Out). To convert a postfix expression into its equivalent prefix form, we need to follow certain rules.

Here are the steps to convert a postfix expression:

  1. Initialize an empty stack.
  2. For each token in the postfix expression:
    • If the token is an operand (number or variable), push it onto the stack.
    • If the token is an operator, pop two operands from the stack and append the operator between them.
  3. The final prefix expression will be the top element on the stack.

For example, if we have the postfix expression 5 2 +, the steps would be:

  1. Initialize an empty stack: []
  2. Push 5 onto the stack: [5]
  3. Push 2 onto the stack: [5, 2]
  4. Pop 2 and push + 5 2: [+]
  5. The final prefix expression is + 5 2.

Time complexity of this algorithm is O(n), where n is the number of tokens in the postfix expression. Space complexity is also O(n) due to the stack.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.Stack;

public class PostfixToPrefix {
    public static String convert(String postfixExpression) {
        Stack<String> stack = new Stack<>();
        StringBuilder prefixExpression = new StringBuilder();

        for (String token : postfixExpression.split(" ")) {
            if (!isOperator(token)) {
                stack.push(token);
            } else {
                prefixExpression.append(stack.pop());
                prefixExpression.append(" ");
                prefixExpression.append(token);
            }
        }

        while (!stack.isEmpty()) {
            prefixExpression.append(stack.pop());
            prefixExpression.append(" ");
        }

        return prefixExpression.toString().trim();
    }

    private static boolean isOperator(String token) {
        // implement your logic to check if the token is an operator
        // for example, you can use a set of known operators
        String[] operators = {"+", "-", "*", "/"};
        for (String operator : operators) {
            if (token.equals(operator)) {
                return true;
            }
        }
        return false;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.