Prefix to Infix & Evaluation of Prefix

HardGFG

Prefix to Infix & Evaluation of Prefix

Pattern:

Idea:

Variations :


πŸ’» Code

It has two parts - See both below . Both are O(n) and O(n) in time and aux. space complexity


Prefix to Infix & Evaluation of Prefix

Tags: #Stack #Expressions #Parsing #Prefix #PolishNotation #Strings #Interview-Pattern #FAANG

Problem Statement

Prefix (Polish Notation) places the operator before its operands.

Two common interview problems are:

  1. Prefix β†’ Infix: Convert a prefix expression into infix.

  2. Evaluate Prefix: Compute the numerical value of a prefix expression.

Examples

PrefixInfixValue
*+ABC(A+B)*Cβ€”
*+235(2+3)*525
-+7*45+20(7+(4Γ—5))-(2+0)25

Prefix Refresher

Unlike postfix, prefix is processed from right to left.

Example:

* + 2 3 5

Think recursively:

      *
     / \
    +   5
   / \
  2   3

Result:

(2+3)*5

This naturally leads to a stack processed right β†’ left.


Part 1 β€” Prefix to Infix

Core Insight

Traverse from right to left.

Whenever an operator appears:

  • Pop the left operand

  • Pop the right operand

  • Combine into (left operator right)

  • Push back

Notice the operand order is opposite to postfix.


Algorithm

For each symbol (right β†’ left):

  • Operand β†’ Push

  • Operator β†’

    • left = pop()

    • right = pop()

    • Push ("(" + left + op + right + ")")

The final stack element is the complete infix expression.


Python Implementation

def prefixToInfix(exp):

    stack = []

    for ch in reversed(exp):

        if ch.isalnum():
            stack.append(ch)

        else:
            left = stack.pop()
            right = stack.pop()

            stack.append("(" + left + ch + right + ")")

    return stack[-1]

Dry Run

Input

*+ABC

Traverse from right:

C B A + *
SymbolStack
CC
BC B
AC B A
+C (A+B)
*((A+B)*C)

Answer:

((A+B)*C)

Why Left Is Popped First?

Consider:

-AB

Desired infix:

A-B

After scanning from right:

Stack:

Top
A
B

Pop order:

left  = A
right = B

Result:

A-B

If reversed, we’d incorrectly obtain B-A.

Mnemonic: Prefix scans right-to-left, so the first pop is the left operand.


Part 2 β€” Evaluation of Prefix

Core Insight

Exactly the same algorithm, but store integers instead of strings.

Traverse from right to left.

Whenever an operator appears:

  1. Pop left operand

  2. Pop right operand

  3. Compute

  4. Push result


Python Implementation

def evaluatePrefix(exp):

    stack = []

    for ch in reversed(exp):

        if ch.isdigit():
            stack.append(int(ch))

        else:
            left = stack.pop()
            right = stack.pop()

            if ch == '+':
                stack.append(left + right)

            elif ch == '-':
                stack.append(left - right)

            elif ch == '*':
                stack.append(left * right)

            else:
                stack.append(int(left / right))

    return stack[-1]

Dry Run

Expression

*+235

Reverse traversal:

5 3 2 + *
SymbolStack
55
35 3
25 3 2
+5 5
*25

Answer:

25

Prefix vs Postfix

Conversion

AspectPrefixPostfix
TraverseRight β†’ LeftLeft β†’ Right
First PopLeftRight
Second PopRightLeft

Evaluation

ExpressionPop Order
PrefixLeft, Right
PostfixRight, Left

This is the only conceptual difference.


Integer Division Caveat

Like LC 150, division truncates toward zero.

Correct:

int(left / right)

Avoid:

left // right

because floor division is incorrect for negative values.


Correctness

Invariant

After processing any suffix of the prefix expression, the stack contains fully constructed subexpressions (or their evaluated values).

Whenever an operator appears:

  • The top two stack elements are exactly its left and right operands.

  • Combining them reconstructs the expression correctly.

Thus the algorithm is correct by induction.


Complexity

ProblemTimeAuxiliary Space
Prefix β†’ InfixO(n)O(n)
Evaluate PrefixO(n)O(n)

Each symbol is pushed and popped exactly once.


Common Mistakes

1. Traversing Left to Right

Prefix must be processed right β†’ left.

Wrong:

*+ABC

Correct traversal:

C B A + *

2. Reversing Operand Order

Wrong:

right = pop()
left = pop()

Correct:

left = pop()
right = pop()

because the traversal is already reversed.

3. Using Floor Division

Use:

int(left / right)

to match truncation toward zero.


Relationship to Expression Problems

ProblemTraverseStack Stores
Infix β†’ PostfixLeft β†’ RightOperators
Infix β†’ PrefixReverse + PostfixOperators
Postfix β†’ InfixLeft β†’ RightStrings
Prefix β†’ InfixRight β†’ LeftStrings
Evaluate PostfixLeft β†’ RightIntegers
Evaluate PrefixRight β†’ LeftIntegers

Together, these six problems form the complete stack-based expression toolkit.


Pattern Recognition

Prefix Conversion

  • Traverse right β†’ left

  • Operand β†’ Push

  • Operator β†’ Pop left, then right, combine

Prefix Evaluation

  • Traverse right β†’ left

  • Operand β†’ Push value

  • Operator β†’ Pop left, right, evaluate

Interview Heuristic: Postfix looks forward, Prefix looks backward. Simply reverse the traversal direction, and the operand pop order flips accordingly.

Local Graph View

Start typing to search
Try: two sum or #Arrays or #Amazon