Skip to content
Think & Reflect · Q3

Q.Write an algorithm to convert an infix expression into equivalent prefix expression using stack.

Puducherry TnboardTextbookSubjective· 5mImportance★★★★★est
92% · 12/13 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

Infix to prefix conversion reverses the expression, applies infix-to-postfix with modified precedence, then reverses the result — all using a stack for operator management.

Why This Algorithm Works

The core idea is elegant: prefix notation (Polish notation) places operators before their operands. Since we read expressions left-to-right, converting directly to prefix is awkward because the operator comes before operands we haven't seen yet. The trick is to reverse the problem.

We reverse the infix expression, swap parentheses (opening becomes closing and vice versa), then run a modified infix-to-postfix algorithm. Finally, we reverse the postfix result to get prefix. This works because postfix places operators after operands — reversing the input and output effectively flips the operator placement.

The Algorithm Steps

Step 1: Reverse the infix expression

  • Reverse the character order of the input string.
  • Swap every ( with ) and every ) with (.

Step 2: Convert the reversed expression to postfix (using a stack)

  • Scan the reversed expression left to right.
  • If character is an operand (letter/digit), add it to output.
  • If character is (, push onto stack.
  • If character is ), pop from stack to output until ( is encountered (discard the ().
  • If character is an operator:
    • While stack is not empty AND top of stack has greater or equal precedence than current operator, pop to output.
    • Push current operator onto stack.
  • After scanning, pop all remaining operators from stack to output.

Step 3: Reverse the postfix expression to get prefix

Important

The precedence order (highest to lowest): ^ (exponentiation), * / (multiplication/division), + - (addition/subtraction). For exponentiation ^, associativity is right-to-left — this matters when precedence is equal.

Watch out

When reversing the expression, parentheses must be swapped. A common mistake is to reverse the string without swapping brackets, which breaks the algorithm completely.

Algorithm in Pseudocode

Algorithm infixToPrefix(infix):
    Input: infix expression as string
    Output: prefix expression as string

    1. reversed ← reverse(infix)
    2. for i from 0 to length(reversed)-1:
           if reversed[i] == '(':
               reversed[i] ← ')'
           else if reversed[i] == ')':
               reversed[i] ← '('

    3. postfix ← infixToPostfix(reversed)   // using modified precedence
    4. prefix ← reverse(postfix)
    5. return prefix

Python Implementation

def precedence(op):
    """Return precedence value of operator."""
    if op == '^':
        return 3
    elif op in ('*', '/'):
        return 2
    elif op in ('+', '-'):
        return 1
    return 0

def is_operator(ch):
    """Check if character is an operator."""
    return ch in ('+', '-', '*', '/', '^')

def infix_to_postfix(expression):
    """Convert infix to postfix using stack."""
    stack = []
    output = []
    
    for ch in expression:
        # Operand: add to output
        if ch.isalnum():  # alphanumeric (letters or digits)
            output.append(ch)
        # Opening bracket: push to stack
        elif ch == '(':
            stack.append(ch)
        # Closing bracket: pop until opening bracket
        elif ch == ')':
            while stack and stack[-1] != '(':
                output.append(stack.pop())
            stack.pop()  # remove '('
        # Operator: handle precedence
        elif is_operator(ch):
            while (stack and stack[-1] != '(' and 
                   precedence(stack[-1]) >= precedence(ch)):
                # For right-associative '^', use > instead of >=
                if ch == '^' and precedence(stack[-1]) == precedence(ch):
                    break
                output.append(stack.pop())
            stack.append(ch)
    
    # Pop remaining operators
    while stack:
        output.append(stack.pop())
    
    return ''.join(output)

def infix_to_prefix(infix):
    """Convert infix expression to prefix."""
    # Step 1: Reverse the infix expression
    reversed_infix = infix[::-1] …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.