![]() |
VOOZH | about |
Given an array of strings arr[] representing a postfix expression, evaluate it. A postfix expression is of the form operand1 operand2 operator (e.g., "a b +"), where two operands are followed by an operator.
Note: The operators can include +, -, *, /, and ^ (where ^ denotes exponentiation, i.e., power). Division / uses floor division.
Examples:
Input: arr[] = ["2", "3", "1", "*", "+", "9", "-"]
Output: -4
Explanation: The expression in infix form is: 2 + (3 * 1) - 9. Now, evaluate step by step:
3 * 1 = 3
2 + 3 = 5
5 - 9 = -4
Final Answer: -4Input: 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
The idea is to use the property of postfix notation, where two operands are always followed by an operator. We iterate through the expression from left to right, and whenever we encounter an operand, we push it onto the stack. When we encounter an operator, we pop the top two elements from the stack, apply the operator on them, and then push the result back into the stack.
Illustration:
-4