712306. Postfix to Infix Conversion

Medium

Postfix to Infix Conversion

Summary

The problem involves converting a given postfix expression into its equivalent infix notation. Postfix expressions are written in reverse Polish notation, where operators follow their operands. The task is to write an algorithm that takes a postfix expression as input and outputs the corresponding infix expression.

Detailed Explanation

To solve this problem, we can use a stack-based approach. We'll iterate through the postfix expression from left to right, and for each token (operand or operator), we'll apply the following rules:

  1. If the token is an operand, add it to the output string as is.
  2. If the token is an operator, pop operands from the stack until you find the matching operator at the top of the stack. Then, add the popped operands and the current operator to the output string.

Here's a step-by-step breakdown:

  1. Initialize an empty stack S and an empty output string result.
  2. Iterate through the postfix expression:
    • For each token (operand or operator):
      • If it's an operand, add it to result.
      • If it's an operator, pop operands from S until you find the matching operator at the top of S. Then, add the popped operands and the current operator to result.
  3. Return the final value of result.

Here's an example:

Postfix expression: A B + C D * Output: ( A + (B * C) * D )

Optimized Solutions

Java

View on GeeksforGeeks
public class PostfixToInfix {
    public static String convert(String postfix) {
        Stack<String> stack = new Stack<>();
        StringBuilder result = new StringBuilder();

        for (String token : postfix.split(" ")) {
            if (token.matches("[a-zA-Z]+")) { // operand
                result.append(token).append(" ");
            } else { // operator
                while (!stack.isEmpty() && !isMatchingOperator(stack.peek(), token)) {
                    result.append(stack.pop()).append(" ");
                }
                stack.push(token);
            }
        }

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

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

    private static boolean isMatchingOperator(String op1, String op2) {
        // implement your matching logic here
        // for example:
        return op1.equals("(") && op2.equals(")");
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.