Evaluation of Postfix Expression | Practice | GeeksforGeeks

Given string S representing a postfix expression, the task is to evaluate the expression and find the final value. Operators will only include the basic arithmetic operators like *, /, + and -.
 
Example 1:
Input: S = "231*+9-"
Output: -4
Explanation:
After solving the given expression, 
we have -4 as result.

Example 2:
Input: S = "123+*8-"
Output: -3
Explanation:
After solving the given postfix 
expression, we have -3 as result.


Your Task:
You do not need to read input or print anything. Complete the function evaluatePostfixExpression() that takes the string S denoting the expression as input parameter and returns the evaluated value.

Expected Time Complexity: O(|S|)
Expected Auixilliary Space: O(|S|)

Constraints:
1 ≤ |S| ≤ 105
0 ≤ |Si|≤ 9 (And given operators)
0
adarsh471112 weeks ago
Java solution
class Solution
{
    //Function to evaluate a postfix expression.
    public static int evaluatePostFix(String s)
    {
        Stack<Integer> st=new Stack<>();
        
        for(int i=0; i<s.length(); i++)
        {
            int var1, var2;
            char ch=s.charAt(i);
            
            if(ch=='+' || ch=='-' || ch=='*' || ch=='/')
            {
                var2=st.pop();
                var1=st.pop();
                switch(ch)
                {
                    case '+':
                        st.push(var1+var2);
                        break;
                    case '-':
                       st.push(var1-var2);
                        break;
                    case '*':
                       st.push(var1*var2);
                        break;
                    case '/':
                       st.push(var1/var2);
                        break;
                }
            }
            else
            st.push(ch-'0');
        }
        return st.pop();
    }
}
0
maneshram20Premium2 weeks ago
Best Ever Easy Understanding Solution in C++
class Solution
{
    bool isOperand(char ch){
        if(ch=='+' or ch=='-' or ch=='*' or ch=='/'){
            return false;
        }
        return true;
    }
    public:
    //Function to evaluate a postfix expression.
    int evaluatePostfix(string str)
    {
        stack<int> st;
        int i=0,j=0,n=str.size();
        for(int i=0;i<n;i++){
            if(isOperand(str[i])){
                st.push(str[i]-'0');
            }
            else{
                int x2 = st.top();
                st.pop();
                int x1 = st.top();
                st.pop();
                switch(str[i]){
                    case '+' : st.push(x1+x2); break;
                    case '-' : st.push(x1-x2); break;
                    case '*' : st.push(x1*x2); break;
                    case '/' : st.push(x1/x2); break;
                }
            }
        }
        return st.top();
    }
};
0
mahesh_phutane3 weeks ago
Suimple java solution using Stack
class Solution
{
    //Function to evaluate a postfix expression.
    public static int evaluatePostFix(String S)
    {
        Stack<Integer> st = new Stack<>();
        for(int i = 0;i<S.length();i++){
            char ch = S.charAt(i);
            if(ch =='*' || ch == '/' || ch =='+' || ch == '-' ){
                int a = st.pop();
                int b = st.pop();
               // System.out.println(a+" "+b+" "+ch);
                evaluate(b,a,ch,st);
            }
            else{
                st.push(ch-'0');
            }
        }
        return st.pop();
    }
    
    public static void evaluate(int a,int b,char ch,Stack<Integer> st){
        switch(ch){
            
            case '*': st.push(a*b);
                    break;
            case '/': st.push(a/b);
                    break;    
            case '+': st.push(a+b);
                    break;
            case '-': st.push(a-b);
                    break;
        }
    }
}
0
akashdsingh0061 month ago
JAVA Code 0.13/1.86
 
   // Your code here       Stack<Integer> inf=new Stack<>();              for(int i=0;i<S.length();i++)       {           char ch=S.charAt(i);           if(Character.isDigit(ch))           {               inf.push(ch-'0');           }           else if(ch=='+'||ch=='-'||ch=='*'||ch=='/')           {                                                   int v2=inf.pop();                   int v1=inf.pop();                   int ans=operation(ch,v1,v2);                   inf.push(ans);               }                          }                     int k=inf.pop();       return k;   }   public static int precedence(char ch)   {       if(ch=='+'||ch=='-')       return 1;       else       return 2;   }   public static int operation(char ch,int a,int b)   {       switch(ch){           case '+':               return a+b;           case '-':               return a-b;           case '*':               return a*b;           case '/':               return a/b;       }              return 0;   }
0
agrawalharshita07111 month ago
class Solution:
    
    #Function to evaluate a postfix expression.
    def evaluatePostfix(self, S):
        #code here
        stk=[]
        for i in S:
            if i.isdigit():
                stk.append(i)
            else:
                a=stk.pop()
                b=stk.pop()
                if i=='+':
                    stk.append(str(int(b)+int(a)))
                if i=='-':
                    stk.append(str(int(b)-int(a)))
                if i=='*':
                    stk.append(str(int(b)*int(a)))
                if i=='/':
                    stk.append(str(int(int(b)/int(a))))
        return stk.pop(0)         
0
gaurabhkumarjha271020011 month ago
stack <int> ss;
          int a=0, b=0;
          
          for (int i=0; i< s.length(); i++){
              
               if (isdigit (s[i]))
                ss.push(s[i]- '0');
                
              
                 switch (s[i]){
                     
                     case '/':
                     a= ss.top(); ss.pop();
                     b= ss.top(); ss.pop();
                     ss.push(b/a);
                      break;
                      
                     case '*':
                     a= ss.top(); ss.pop();
                     b= ss.top(); ss.pop();
                     ss.push(b*a);
                      break;
                     
                     case '+':
                     a= ss.top(); ss.pop();
                     b= ss.top(); ss.pop();
                     ss.push(b+a);
                      break;
                    
                    case '-':
                     a= ss.top(); ss.pop();
                     b= ss.top(); ss.pop();
                     ss.push(b-a);
                      break; 
                     
                 }  
            }
            
             return ss.top();
0
gaurabhkumarjha271020011 month ago
// easy c++ code 
   stack <int> ss;
   int a=0, b=0;
          
    for (int i=0; i< s.length(); i++){
              
         if (isdigit (s[i]))
          ss.push(s[i]- '0');
                
              
                 switch (s[i]){
                     
                     case '/':
                     a= ss.top(); ss.pop();
                     b= ss.top(); ss.pop();
                     ss.push(b/a);
                      break;
                      
                     case '*':
                     a= ss.top(); ss.pop();
                     b= ss.top(); ss.pop();
                     ss.push(b*a);
                      break;
                     
                     case '+':
                     a= ss.top(); ss.pop();
                     b= ss.top(); ss.pop();
                     ss.push(b+a);
                      break;
                    
                    case '-':
                     a= ss.top(); ss.pop();
                     b= ss.top(); ss.pop();
                     ss.push(b-a);
                      break; 
                     
                 }  
            }
            
             return ss.top();
0
tarunkanade1 month ago
0.1/1.9
public static int evaluatePostFix(String S)
    {
        // Your code here
        ArrayDeque<Integer> stack = new ArrayDeque<>();
        int res = 0;
        
        for(int i=0; i<S.length(); i++){
            char c = S.charAt(i);
            
            if(Character.isDigit(c)){
                stack.push(Character.getNumericValue(c));
            }
            else{
                int b = stack.pop();
                int a = stack.pop();
                
                res = evaluate(a, c, b);
                stack.push(res);
            }
        }
        
        return stack.pop();
    }
    
    private static int evaluate(int a, char op, int b){
        
        switch(op){
            case '+':
                return a+b;
            case '-':
                return a-b;
            case '*':
                return a*b;
            case '/':
                return a/b;
        }
        
        return 0;
    } 
+1
amar_raj2 months ago
  //Time Taken =0.0 Sec//
  //C++ easy Solution// 
  stack<int> st;
         for(auto x:S)
         {
             if(x>='0'&&x<='9')
             {
                 st.push(x-'0');
             }
             else
             {
                int a=st.top();
                st.pop();
                int b=st.top();
                st.pop();
                if(x=='*'){
                
                st.push((b*a));
                }
                else if(x=='/'){
                
                st.push((b/a));
                }
                else if(x=='+'){
                
                st.push((b+a));
                }
                
                else
                {
                    st.push((b-a));
                }
             }
         }
         return st.top();
-1
nishitchaudhary00552 months ago
class Solution:      def __init__(self):       self.stack = []          def isEmpty(self):       return self.stack == []          def push(self,op):       self.stack.append(op)      def pop(self):       if not self.isEmpty():           return self.stack.pop()       else:           return '$'      #Function to evaluate a postfix expression.   def evaluatePostfix(self, S):       for i in S:           if(i.isdigit()):               self.push(i)           else:               a = self.pop()               b = self.pop()               self.push(str(eval(b+i+a)))                          return int(self.pop())            
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.