16. Postfix Evaluation
β GFG solution to the Postfix Evaluation problem: evaluate arithmetic expressions written in Reverse Polish Notation using stack data structure. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given an array of strings arr[]
that represents a valid arithmetic expression written in Reverse Polish Notation (Postfix Notation). Your task is to evaluate the expression and return an integer representing its value.
Note: A postfix expression is of the form operand1 operand2 operator
(e.g., "a b +"). The division operation between two integers always computes the floor value, i.e floor(5 / 3) = 1
and floor(-5 / 3) = -2
. It is guaranteed that the result of the expression and all intermediate calculations will fit in a 32-bit signed integer.
π Examples
Example 1
Input: arr[] = ["2", "3", "1", "*", "+", "9", "-"]
Output: -4
Explanation: If the expression is converted into an infix expression, it will be 2 + (3 * 1) β 9 = 5 β 9 = -4.
Example 2
Input: arr[] = ["2", "3", "^", "1", "+"]
Output: 9
Explanation: If the expression is converted into an infix expression, it will be 2 ^ 3 + 1 = 8 + 1 = 9.
π Constraints
$3 \le \text{arr.size()} \le 10^3$
arr[i]
is either an operator: "+", "-", "*", "/" or "^", or an integer in the range $[-10^4, 10^4]$
β
My Approach
The optimal approach uses a Stack data structure to efficiently evaluate postfix expressions:
Stack-Based Evaluation
Initialize Stack:
Create an empty stack to store operands during evaluation.
Process Each Token:
Iterate through each element in the array from left to right.
If the token is an operand (number), push it onto the stack.
If the token is an operator, pop two operands from the stack.
Perform Operation:
Pop the second operand (
b
) first, then the first operand (a
).Apply the operator:
a operator b
.Handle special division case for floor division with negative numbers.
Push the result back onto the stack.
Return Result:
After processing all tokens, the stack contains exactly one element - the final result.
Key Insight:
Postfix notation eliminates the need for parentheses and operator precedence rules. The stack naturally handles the order of operations by processing operands and operators in the correct sequence.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the size of the array. We traverse each element exactly once and perform constant time operations (push, pop, arithmetic) for each element.
Expected Auxiliary Space Complexity: O(k), where k is the maximum number of operands that can be stored on the stack simultaneously. In the worst case, k can be up to n/2 for expressions with many consecutive operands.
π§ Code (C)
int evaluate(char* arr[], int size) {
int stack[size], top = -1;
for (int i = 0; i < size; i++) {
char* t = arr[i];
if (strlen(t) == 1 && strchr("+-*/^", t[0])) {
int b = stack[top--], a = stack[top--];
if (t[0] == '/') stack[++top] = (a < 0) ^ (b < 0) && a % b ? a / b - 1 : a / b;
else stack[++top] = t[0] == '+' ? a + b : t[0] == '-' ? a - b :
t[0] == '*' ? a * b : (int)pow(a, b);
} else stack[++top] = atoi(t);
}
return stack[top];
}
π§βπ» Code (C++)
class Solution {
public:
int evaluatePostfix(vector<string>& arr) {
stack<int> st;
for (const auto& t : arr) {
if (t.size() == 1 && strchr("+-*/^", t[0])) {
int b = st.top(); st.pop();
int a = st.top(); st.pop();
if (t[0] == '/') st.push((a < 0) ^ (b < 0) && a % b ? a / b - 1 : a / b);
else st.push(t[0] == '+' ? a + b : t[0] == '-' ? a - b :
t[0] == '*' ? a * b : pow(a, b));
} else st.push(stoi(t));
}
return st.top();
}
};
β Code (Java)
class Solution {
public int evaluatePostfix(String[] arr) {
Stack<Integer> st = new Stack<>();
for (String t : arr) {
if (t.length() == 1 && "+-*/^".contains(t)) {
int b = st.pop(), a = st.pop();
if (t.equals("/")) st.push((a < 0) ^ (b < 0) && a % b != 0 ? a / b - 1 : a / b);
else st.push(t.equals("+") ? a + b : t.equals("-") ? a - b :
t.equals("*") ? a * b : (int)Math.pow(a, b));
} else st.push(Integer.parseInt(t));
}
return st.peek();
}
}
π Code (Python)
class Solution:
def evaluatePostfix(self, arr):
st = []
for t in arr:
if t in "+-*/^" and len(t) == 1:
b, a = st.pop(), st.pop()
if t == '/':
st.append(a // b)
else:
st.append(a + b if t == '+' else a - b if t == '-' else
a * b if t == '*' else a ** b)
else:
st.append(int(t))
return st[-1]
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated