712234. Prefix to Infix Conversion

Medium

Prefix to Infix Conversion

Summary

The Prefix to Infix Conversion problem involves transforming a mathematical expression written in prefix notation (also known as Polish notation) into infix notation. This problem requires understanding of the fundamental concepts of operator precedence, parentheses, and order of operations.

Detailed Explanation

The input is a string representing a mathematical expression in prefix notation. The goal is to convert this expression into infix notation, which is more readable and understandable for humans. To achieve this, we need to follow certain rules:

  1. For every binary operator (like +, -, *, /) encountered in the prefix notation, insert parentheses around the operator and its operands.
  2. The operands should be evaluated first according to their order of operations.

Here is a step-by-step breakdown of the solution:

  1. Initialize an empty string result to store the infix expression.
  2. Iterate through the input string from right to left (start with the last character).
  3. If the current operator is a binary operator, insert parentheses around it and its operands in the result string.
  4. For each operand encountered, evaluate it according to its order of operations and append it to the result string.
  5. Continue this process until all characters have been processed.

Time Complexity: O(n), where n is the length of the input string. Space Complexity: O(n), as in the worst-case scenario we might need to store all characters in the result string.

Optimized Solutions

Java

View on GeeksforGeeks
public class PrefixToInfix {
    public static String convert(String prefix) {
        StringBuilder infix = new StringBuilder();
        for (int i = prefix.length() - 1; i >= 0; i--) {
            char c = prefix.charAt(i);
            if (isOperator(c)) {
                infix.insert(0, "(").insert(0, c).append(")");
            } else {
                infix.insert(0, c);
            }
        }
        return infix.toString();
    }

    private static boolean isOperator(char c) {
        String operators = "+-*/";
        return operators.indexOf(c) != -1;
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.