Open In App

Convert Infix To Prefix Notation

Last Updated : 03 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an infix expression consisting of operators (+, -, *, /, ^) and operands (lowercase characters), the task is to convert it to a prefix expression.

Infix Expression: The expression of type a 'operator' b (a+b, where + is an operator) i.e., when the operator is between two operands.

Prefix Expression: The expression of type 'operator' a b (+ab where + is an operator) i.e., when the operator is placed before the operands.

Examples: 

Input: a*b+c/d
Output: +*ab/cd 

Input: (a-b/c)*(a/k-l)
Output: *-a/bc-/akl

Approach:

The idea is to first reverse the given infix expression while swapping '(' with ')' and vice versa, then convert this modified expression to postfix notation using a stack-based approach that follows operator precedence and associativity rules, and finally reverse the obtained postfix expression to get the prefix notation.

Step by step approach:

  1. Reverse the infix expression. Note while reversing each '(' will become ')' and each ')' becomes '('.
  2. Convert the reversed infix expression to postfix expression.
    • Initialize an empty stack to store operators and an empty string for the postfix expression.
    • Scan the infix expression from left to right.
    • If the character is an operand, append it to the postfix expression.
    • If the character is '(', push it onto the stack.
    • If the character is ')', pop from the stack and append to the postfix expression until '(' is found, then pop '(' without appending.
    • If the character is an operator, pop and append operators from the stack until the stack is empty or a lower precedence operator is found, then push the current operator onto the stack.
    • After scanning the expression, pop and append all remaining operators from the stack to the postfix expression.
  3. Reverse the postfix expression and return it.

Illustration:

See the below image for a clear idea:

Convert infix expression to prefix expression
Convert infix expression to prefix expression

Below is implementation of the above approach:

C++
// C++ program to convert infix to prefix
#include <bits/stdc++.h>
using namespace std;

// Check if character is an operator
bool isOperator(char ch) {
    return (ch == '+' || ch == '-' || 
    ch == '*' || ch == '/' || ch == '^');
}

// Get precedence of operators
int operatorPrecedence(char op) {
    if (op == '^') return 3;
    if (op == '*' || op == '/') return 2;
    if (op == '+' || op == '-') return 1;
    return -1;
}

// Convert infix expression to postfix notation
string convertInfixToPostfix(string s) {
    stack<char> st;
    string res;
    int sz = s.size();

    for (int i = 0; i < sz; i++) {
        if (isalnum(s[i])) {
            res += s[i];
        } else if (s[i] == '(') {
            st.push(s[i]);
        } else if (s[i] == ')') {
            while (!st.empty() && st.top() != '(') {
                res += st.top();
                st.pop();
            }
            st.pop();
        } else {
            while (!st.empty() && operatorPrecedence(s[i]) <= 
            operatorPrecedence(st.top())) {
                res += st.top();
                st.pop();
            }
            st.push(s[i]);
        }
    }

    while (!st.empty()) {
        res += st.top();
        st.pop();
    }

    return res;
}

// Convert infix expression to prefix notation
string convertToPrefix(string infix) {
    reverse(infix.begin(), infix.end());

    for (int i = 0; i < infix.size(); i++) {
        if (infix[i] == '(') {
            infix[i] = ')';
        } else if (infix[i] == ')') {
            infix[i] = '(';
        }
    }

    string postfix = convertInfixToPostfix(infix);
    reverse(postfix.begin(), postfix.end());

    return postfix;
}

int main() {
    string s = "(a-b/c)*(a/k-l)";
    cout << convertToPrefix(s) << endl;
    return 0;
}
Java
// Java program to convert infix to prefix
import java.util.*;

class GfG {

    // Check if character is an operator
    static boolean isOperator(char ch) {
        return (ch == '+' || ch == '-' || 
                ch == '*' || ch == '/' || ch == '^');
    }

    // Get precedence of operators
    static int operatorPrecedence(char op) {
        if (op == '^') return 3;
        if (op == '*' || op == '/') return 2;
        if (op == '+' || op == '-') return 1;
        return -1;
    }

    // Convert infix expression to postfix notation
    static String convertInfixToPostfix(String s) {
        Stack<Character> st = new Stack<>();
        StringBuilder res = new StringBuilder();
        int sz = s.length();

        for (int i = 0; i < sz; i++) {
            if (Character.isLetterOrDigit(s.charAt(i))) {
                res.append(s.charAt(i));
            } else if (s.charAt(i) == '(') {
                st.push(s.charAt(i));
            } else if (s.charAt(i) == ')') {
                while (!st.isEmpty() && st.peek() != '(') {
                    res.append(st.pop());
                }
                st.pop();
            } else {
                while (!st.isEmpty() && operatorPrecedence(s.charAt(i)) <= 
                operatorPrecedence(st.peek())) {
                    res.append(st.pop());
                }
                st.push(s.charAt(i));
            }
        }

        while (!st.isEmpty()) {
            res.append(st.pop());
        }

        return res.toString();
    }

    // Convert infix expression to prefix notation
    static String convertToPrefix(String infix) {
        StringBuilder sb = new StringBuilder(infix);
        sb.reverse();
        infix = sb.toString();

        char[] chars = infix.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '(') {
                chars[i] = ')';
            } else if (chars[i] == ')') {
                chars[i] = '(';
            }
        }

        String postfix = convertInfixToPostfix(new String(chars));
        return new StringBuilder(postfix).reverse().toString();
    }

    public static void main(String[] args) {
        String s = "(a-b/c)*(a/k-l)";
        System.out.println(convertToPrefix(s));
    }
}
Python
# Python program to convert infix to prefix

# Check if character is an operator
def isOperator(ch):
    return ch in ['+', '-', '*', '/', '^']

# Get precedence of operators
def operatorPrecedence(op):
    if op == '^':
        return 3
    if op in ['*', '/']:
        return 2
    if op in ['+', '-']:
        return 1
    return -1

# Convert infix expression to postfix notation
def convertInfixToPostfix(s):
    st = []
    res = ""
    sz = len(s)

    for i in range(sz):
        if s[i].isalnum():
            res += s[i]
        elif s[i] == '(':
            st.append(s[i])
        elif s[i] == ')':
            while st and st[-1] != '(':
                res += st.pop()
            st.pop()
        else:
            while st and operatorPrecedence(s[i]) <= operatorPrecedence(st[-1]):
                res += st.pop()
            st.append(s[i])

    while st:
        res += st.pop()

    return res

# Convert infix expression to prefix notation
def convertToPrefix(infix):
    infix = infix[::-1]
    infix = ''.join(['(' if ch == ')' else ')' if ch == '(' else ch for ch in infix])
    
    postfix = convertInfixToPostfix(infix)
    return postfix[::-1]

if __name__ == "__main__":
    s = "(a-b/c)*(a/k-l)"
    print(convertToPrefix(s))
C#
// C# program to convert infix to prefix
using System;
using System.Collections.Generic;

class GfG {

    // Check if character is an operator
    static bool isOperator(char ch) {
        return (ch == '+' || ch == '-' || 
                ch == '*' || ch == '/' || ch == '^');
    }

    // Get precedence of operators
    static int operatorPrecedence(char op) {
        if (op == '^') return 3;
        if (op == '*' || op == '/') return 2;
        if (op == '+' || op == '-') return 1;
        return -1;
    }

    // Convert infix expression to postfix notation
    static string convertInfixToPostfix(string s) {
        Stack<char> st = new Stack<char>();
        string res = "";
        int sz = s.Length;

        for (int i = 0; i < sz; i++) {
            if (char.IsLetterOrDigit(s[i])) {
                res += s[i];
            } else if (s[i] == '(') {
                st.Push(s[i]);
            } else if (s[i] == ')') {
                while (st.Count > 0 && st.Peek() != '(') {
                    res += st.Pop();
                }
                st.Pop();
            } else {
                while (st.Count > 0 && operatorPrecedence(s[i]) <= 
                operatorPrecedence(st.Peek())) {
                    res += st.Pop();
                }
                st.Push(s[i]);
            }
        }

        while (st.Count > 0) {
            res += st.Pop();
        }

        return res;
    }

    // Convert infix expression to prefix notation
    static string convertToPrefix(string infix) {
        char[] arr = infix.ToCharArray();
        Array.Reverse(arr);
        infix = new string(arr);

        for (int i = 0; i < arr.Length; i++) {
            if (arr[i] == '(') {
                arr[i] = ')';
            } else if (arr[i] == ')') {
                arr[i] = '(';
            }
        }

        string postfix = convertInfixToPostfix(new string(arr));
        char[] postArr = postfix.ToCharArray();
        Array.Reverse(postArr);
        return new string(postArr);
    }

    static void Main(string[] args) {
        string s = "(a-b/c)*(a/k-l)";
        Console.WriteLine(convertToPrefix(s));
    }
}
JavaScript
// JavaScript program to convert infix to prefix

// Check if character is an operator
function isOperator(ch) {
    return ['+', '-', '*', '/', '^'].includes(ch);
}

// Get precedence of operators
function operatorPrecedence(op) {
    if (op === '^') return 3;
    if (op === '*' || op === '/') return 2;
    if (op === '+' || op === '-') return 1;
    return -1;
}

// Convert infix expression to postfix notation
function convertInfixToPostfix(s) {
    let st = [];
    let res = "";
    
    for (let i = 0; i < s.length; i++) {
        if (/[a-zA-Z0-9]/.test(s[i])) {
            res += s[i];
        } else if (s[i] === '(') {
            st.push(s[i]);
        } else if (s[i] === ')') {
            while (st.length && st[st.length - 1] !== '(') {
                res += st.pop();
            }
            st.pop();
        } else {
            while (st.length && operatorPrecedence(s[i]) <= operatorPrecedence(st[st.length - 1])) {
                res += st.pop();
            }
            st.push(s[i]);
        }
    }

    while (st.length) {
        res += st.pop();
    }

    return res;
}

// Convert infix expression to prefix notation
function convertToPrefix(infix) {
    let reversed = infix.split("").reverse().join("");
    reversed = reversed.replace(/\(/g, 'X').replace(/\)/g, '(').replace(/X/g, ')');

    let postfix = convertInfixToPostfix(reversed);
    return postfix.split("").reverse().join("");
}

let s = "(a-b/c)*(a/k-l)";
console.log(convertToPrefix(s));

Output
*-a/bc-/akl

Complexity Analysis:

  • Time Complexity: O(n)
    • Stack operations like push() and pop() are performed in constant time. 
    • Since we scan all the characters in the expression once the complexity is linear in time
  • Auxiliary Space: O(n) because we are keeping a stack.

Next Article
Practice Tags :

Similar Reads