Problem of the day
An expression is called the postfix expression if the operator appears in the expression after the operands.
Example :
Infix expression: A + B * C - D
Postfix expression: A B + C D - *
Given a postfix expression, the task is to evaluate the expression. The answer could be very large, output your answer modulo (10^9+7). Also, use modular division when required.
Note:1. Operators will only include the basic arithmetic operators like '*', '/', '+', and '-'.
2. The operand can contain multiple digits.
3. The operators and operands will have space as a separator between them.
4. There won’t be any brackets in the postfix expression.
The first line of input contains an integer ‘T’ denoting the number of test cases.
The next ‘T’ lines represent the ‘T’ test cases.
The first and only line of each test case contains a postfix expression.
Output format
For each test case, print an integer obtained by evaluating the given postfix expression.
Note:
You are not required to print the expected output; it has already been taken care of, Just implement the function.
1 <= T <= 100
1 <= N <= 10^3
1 <= NUM <= 100
Where ‘N’ denotes the length of postfix expression and ‘NUM’ denotes the operand.
Time Limit: 1 sec
2
2 3 1 * + 9 -
1 2 3 + * 8 -
-4
-3
Test case 1:
2 3 1 * + 9 -
- : ( ) - ( )
9 : ( ) - (9)
+ : ( ( ) + ( ) ) - (9)
'*': ( ( ) + ( ( ) * ( ) ) ) - (9)
1 : ( ( ) + ( ( ) * (1) ) ) - (9)
3 : ( ( ) + ( (3) * (1) ) ) - (9)
2 : ( (2) + ( (3) * (1) ) ) - (9)
Result = (2 + 3) - 9 = 5 - 9 = -4
Test case 2:
1 2 3 + * 8 -
- : ( ) - ( )
8 : ( ) - (8)
* : ( ( ) * ( ) ) - (8)
+ : ( ( ) * ( ( ) + ( ) ) ) - (8)
3 : ( ( ) * ( ( ) + (3) ) ) - (8)
2 : ( ( ) * ( (2) + (3) ) ) - (8)
1 : ( (1) * ( (2) + (3) ) ) - (8)
Result = (1 * 5) - 8 = 5 - 8 = -3
1
100 200 + 2 / 5 * 7 +
757
100 + 200 = 300
300 / 2 = 150
150 * 5 = 750
750 + 7 = 757
Try using stack.
The idea is to use a stack to store the operands. Whenever an operator is encountered, we pop the top two numbers from the stack, perform the operation and push the result back to the stack. Finally, when the traversal is completed, the number left in the stack is the final answer.
O(N), where ‘N’ is the length of the postfix expression.
Since we are iterating over the postfix expression of length ‘N’ and so, the overall time complexity is O(N).
O(N), where ‘N’ is the length of the postfix expression.
Since we are using a stack to store the elements of the given expression and so, the overall space complexity is O(N).