Infix to Postfix | Practice | GeeksforGeeks

Given an infix expression in the form of string str. Convert this infix expression to postfix expression.
Infix expression: The expression of the form a op b. When an operator is in-between every pair of operands.
Postfix expression: The expression of the form a b op. When an operator is followed for every pair of operands.
Note: The order of precedence is: ^ greater than * equals to / greater than + equals to -. 
Example 1:
Input: str = "a+b*(c^d-e)^(f+g*h)-i"
Output: abcd^e-fgh*+^*+i-
Explanation:
After converting the infix expression 
into postfix expression, the resultant 
expression will be abcd^e-fgh*+^*+i-

Example 2:
Input: str = "A*(B+C)/D"
Output: ABC+*D/
Explanation:
After converting the infix expression 
into postfix expression, the resultant 
expression will be ABC+*D/
 
Your Task:
This is a function problem. You only need to complete the function infixToPostfix() that takes a string(Infix Expression) as a parameter and returns a string(postfix expression). The printing is done automatically by the driver code.
Expected Time Complexity: O(|str|).
Expected Auxiliary Space: O(|str|).
Constraints:
1 ≤ |str| ≤ 105
0
abhijeet194032 weeks ago
This is a simple approach in C++
 
unordered_map<char,int> m; // map to find the precedence   Solution()   {       m.insert({'^',3});       m.insert({'*',2});       m.insert({'/',2});       m.insert({'+',1});       m.insert({'-',1});       m.insert({'(',0});   }   string infixToPostfix(string s) {       string res="";// to store the final result        stack<char> st; // make a stack       for(auto x:s) // traversing the given string from left to right       {           if(x>=65 && x<=90 || x>=97&&x<=122)           res = res + x;// if the character is a variable then add it to result           else if(x=='(')           st.push(x);           else if(x==')') // if a closing bracket is encountered pop all the elements till an opening bracket is encountered           {               while(st.top()!='(')               {                   char ch = st.top();                   res = res + ch;                   st.pop();               }               st.pop();           }           else           {               while(!st.empty() && m[x]<=m[st.top()]) // pop and add to result till all the higher order operators are removed from stack               {                   res=res+st.top();;                   st.pop();               }               st.push(x);           }       }       while(!st.empty()) // pop all remaining elements and add to result       {           res = res+st.top();           st.pop();       }       return res;   }
0
ajay256413 weeks ago
Java solution
 // Function to convert an infix expression to a postfix expression.
    public static String infixToPostfix(String str) {
        int n=str.length();
        String res=new String("");
        Stack<Character> s = new Stack<>();
        for(int i=0;i<n;i++){
            char ch=str.charAt(i);
            if((ch>=97&&ch<=122)||(ch>=65&&ch<=90)) res+=ch;
            else if(ch=='(') s.push(ch);
            else if(ch==')'){
                while(s.peek()!='(') res+=s.pop();
                s.pop();
            }
            else if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='^'){
                   while(!s.isEmpty()&&checkPrecedence(s.peek(),ch)!=1)
                           res+=s.pop();
                    s.push(ch);   
            }
        }
        while(s.isEmpty()==false){
            res+=s.pop();
        }
        return res;
    }
    static int checkPrecedence(char stop,char ch){
        int a=precedenceHelper(ch);
        int b=precedenceHelper(stop);
        if(a>b) return 1;
        else if(a<b) return 0;
        else return -1;
    }
    static int precedenceHelper(char ch){
        if(ch=='(') return 1;
        else if(ch=='+'||ch=='-') return 2;
        else if(ch=='*'||ch=='/') return 3;
        else return 4;  
    }
0
akashdsingh0064 weeks ago
Java Code
 
     // Your code here       Stack<Character> ops=new Stack<>();       Stack<String> post=new Stack<>();       for(int i=0;i<exp.length();i++)       {           char ch=exp.charAt(i);           if(ch=='(')           {               ops.push(ch);           }           else if(Character.isLetterOrDigit(ch))           {               post.push(ch+"");           }           else if(ch==')')           {               while(ops.peek()!='(' && ops.size()>0)               {                   char op=ops.pop();                   String v2=post.pop();                   String v1=post.pop();                   post.push(v1+v2+op);               }               ops.pop();           }           else if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch=='^') {       while (ops.size() > 0 && ops.peek() != '(' && precedence(ch) <= precedence(ops.peek())) {         char op = ops.pop();
         String v2 = post.pop();         String v1 = post.pop();         post.push(v1 + v2 + op);       }       ops.push(ch);           }       }   while(ops.size()>0)   {       char op = ops.pop();
         String v2 = post.pop();         String v1 = post.pop();         post.push(v1 + v2 + op);   }   String t=post.pop();   return t;       }private static int precedence(char ch){    if(ch == '+' || ch == '-')        return 1;    else if(ch == '*' || ch == '/')        return 2;    else if( ch == '^')        return 3;    else        return -1;}
+1
videhnandini751 month ago
C++ | Fast and Efficient

class Solution {
  public:
    // Function to convert an infix expression to a postfix expression.
    int precedence(char op) {
        if(op == '+' || op == '-') {
            return 1;
        }
        else if(op == '*' || op == '/') {
            return 2;
        }
        else {
            return 3;
        }
    }
    
    // Function to convert an infix expression to a postfix expression.
    string infixToPostfix(string s) {
         // Your code here
        // int len = s.length();
        stack <string> post;
        // stack <string> pre;
        stack <char> op;
        string str = "";
        
        for(int i=0;i<s.length();i++) {
            
            char ch = s[i];
            if(ch == '(') {
                op.push(ch);
            }
            else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
                str.push_back(ch);
                post.push(str);
            }
            else if(ch == ')') {
                while(op.top() != '(') {
                    char opr = op.top();
                    op.pop();
                    string v2 = post.top();
                    post.pop();
                    
                    str =  v2 + opr;
                    post.push(str);
                }
                op.pop();
            }
            else if(ch == '^' || ch == '+' || ch == '-' || ch == '*' || ch == '/' ) {
                 while(!op.empty() && op.top() != '(' && precedence(ch) <= precedence(op.top())) {
                    char opr = op.top();
                    op.pop();
                    string v2 = post.top();
                    post.pop();
                   //cout<<v2<<" ";
                    str = v2+opr;
                    //cout<<str<<" ";
                    post.push(str);
                }
                op.push(ch);
            }
        }
        
        while(op.size() > 0) {
            char opr = op.top();
            op.pop();
            string v2 = post.top();
            post.pop();
            
            str =  v2 + opr;
            post.push(str);
        }
        return post.top();
    }
};
0
tarunkanade1 month ago
0.2/1.2
public static String infixToPostfix(String exp) 
	{
		// Your code here
		String res = "";
		ArrayDeque<Character> stack = new ArrayDeque<>();
		
		for(int i=0; i<exp.length(); i++){
		    char c = exp.charAt(i);
		    
		    if(c == '+' || c == '-' || c == '*' || c == '/' || c == '^'){
	            while(!stack.isEmpty() && getPre(stack.peek()) >= getPre(c))
	                res += stack.pop();
	            stack.push(c);
		    }
		    else if(c == '('){
		        stack.push(c);
		    }
		    else if(c == ')'){
		        while(stack.peek() != '('){
		            res += stack.pop();
		        }
		        stack.pop();
		    }
		    else{
		        res += c;
		    }
		}
		
		while(!stack.isEmpty())
		    res += stack.pop();
		return res;
	} 
	
	private static int getPre(char op){
	    switch(op){
	        case '+': case '-':
	            return 1;
	        case '*': case '/':
	            return 2;
	        case '^':
	            return 3;
	    }
	    
	    return -1;
	}
0
jankinair73
This comment was deleted.
0
sushantsde2 months ago
 int pr(char s){       if(s=='(') return 0;       else if(s=='+' || s=='-') return 1;       else if(s=='*' || s=='/' || s=='%') return 2;       else if(s=='^') return 3;       return 0;    }   string infixToPostfix(string s)   {   int a=s.length();   string sa="";   stack <char> st;   for(int i=0;i<a;i++){       if(s[i]>='a'&&s[i]<='z'){           sa+=s[i];       }       else if(s[i]=='('){           st.push('(');       }       else if(s[i]==')'){           while(st.top()!='('){               sa+=st.top();               st.pop();           }           st.pop();       }       else{           while(!st.empty()&&pr(st.top())>=pr(s[i]) &&s[i]!='^'){               sa+=st.top();               st.pop();           }           st.push(s[i]);       }   }   while(!st.empty()){       sa+=st.top();       st.pop();   }   return sa;   }
0
imohdalam2 months ago
Java | O(n)
public static String infixToPostfix(String exp) 
	{
		String result = "";
		Stack<Character> stack = new Stack<Character>();
		for(int i=0; i<exp.length(); i++){
		    
		    char ch = exp.charAt(i);
		    
		    if(Character.isLetterOrDigit(ch)){
		        result += ch;
		    }else if(ch == '('){
		        stack.push(ch);
		    }else if(ch == ')'){
		        while(!stack.isEmpty() && stack.peek() != '('){
		            result += stack.pop();
		        }
		        stack.pop();
		    }else{
		        while(!stack.isEmpty() 
		               && precedence(ch) <=               precedence(stack.peek())
		               && isLeftToRightAssociative(ch)){
		            result += stack.pop();
		        }
		        stack.push(ch);
		    }
		}
		
		while(!stack.isEmpty()){
		    result += stack.pop();
		}
		
		return result;
	}
	
	private static int precedence(char ch){
	    if(ch == '+' || ch == '-')
	        return 1;
	    else if(ch == '*' || ch == '/')
	        return 2;
	    else if( ch == '^')
	        return 3;
	    else
	        return -1;
	}
	
	private static boolean isLeftToRightAssociative(char ch){
	    return ch != '^';
	}
-4
varshithkotha0073 months ago
def InfixtoPostfix(self, exp):       #code here       pre={}       pre['^']=4       pre['*']=3       pre['/']=3       pre['+']=2       pre['-']=2       pre['(']=1       operand="abcdefghijklmnopqrstuvwxyz"       op="ABCDEFGHIJKLMNOPQRSTUVWXYZ"       stack=[]       l=[]       result=""       for j in exp:           l.append(j)       for i in range(0,len(l)):           if l[i] in operand or l[i] in op:               result+=l[i]           elif l[i]=="(":               stack.append(l[i])           elif l[i]==")":               while stack[-1]!="(":                   result=result+stack.pop()               stack.pop()           else:               if stack==[] or pre[l[i]]>pre[stack[-1]]:                   stack.append(l[i])               elif pre[l[i]]<=pre[stack[-1]] and l[i]!="^":                   while stack!=[] and stack[-1]!="(":                       result=result+stack.pop()                   stack.append(l[i])               elif l[i]=="^" and pre[l[i]]==pre[stack[-1]]:                   stack.append(l[i])       while stack!=[]:           result=result+stack.pop()       return result
+2
mdadkh0003 months ago
Use one more method for ^ bcz its associtivity is from right to left that's most of the people getting wrong an in a^b^c. But the gfg compiler is showing us correct o/p abc^^ 
 
Below is my algo implementation 
  //  IMP method
   public static boolean isLeftToRightAssociative(Character operator)     {       if (operator == '^')         return false;       else          return true;     }      //Function to convert an infix expression to a postfix expression.public static String infixToPostfix(String exp) { // Your code here       String result = "";              Stack<Character> stack = new Stack<>();               for (int i = 0; i<exp.length(); ++i)       {           char c = exp.charAt(i);                     if (Character.isLetterOrDigit(c))               result += c;                        else if (c == '(')               stack.push(c);                       else if (c == ')')           {               while (!stack.isEmpty() && stack.peek() != '(')                   result += stack.pop();                                   stack.pop();           }           else            {               while (!stack.isEmpty() && Prec(c)<= Prec(stack.peek()) &&                                      isLeftToRightAssociative(stack.peek()) )                  result += stack.pop();                               stack.push(c);           }            }            while (!stack.isEmpty()){           if(stack.peek() == '(')               return "Invalid Expression";           result += stack.pop();        }       return result;} public static int Prec(char ch)   {       switch (ch)       {       case '+':       case '-':           return 1;            case '*':       case '/':           return 2;            case '^':           return 3;       }       return -1;   }  
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.