Introduction
Evaluate Postfix Expression means calculating the final result of a postfix mathematical expression.
Postfix notation:
23*54*+9- In postfix notation:
- operators come after operands
The task is to:
- evaluate the final numerical result
Example:
Input: 23*54*+9-Output: 17
Explanation:
2 * 3 = 65 * 4 = 20
6 + 20 = 26
26 - 9 = 17
This problem is one of the most important applications of:
Stack Data Structure Constraints
Expression contains:
Operands:
0-9
Operators:
+, -, *, /Expression is valid.
Approach 1 : Brute Force (Manual Evaluation)
Explanations:
Explanation:
The idea is to manually evaluate operators step by step.
Steps:
- Traverse expression.
- Find operator.
- Evaluate nearby operands.
- Replace expression repeatedly.
This approach becomes difficult for:
- long expressions
- nested operations
- large inputs
So stack-based evaluation is preferred.
Dry Run
Input:23*54*+9-
Step 1:
2 * 3 = 6
Expression:
654*+9-
Step 2:
5 * 4 = 20
Expression:
620+9-
Step 3:
6 + 20 = 26
Expression:
269-
Step 4:
26 - 9 = 17
Final Output:
17
Practice :
Complexity Analysis :
Time Complexity:- O(n)Explanation :
Expression is traversed once.
Space Complexity:- O(n)
Explanation :
Stack stores operands.
Approach 2 : Optimal Solution(Using Stack)
Explanations:
Explanation:
This is the most optimized and interview-preferred solution.
The idea is:
- push operands into stack
- when operator appears:
- pop two operands
- perform operation
- push result back
At the end:
- stack contains final answer
This efficiently evaluates postfix expressions.
Dry Run
Input:23*54*+9-
Step 1:
Push 2
Stack:
[2]
Step 2:
Push 3
Stack:
[2, 3]
Step 3:
* operator
2 * 3 = 6
Stack:
[6]
Step 4:
Push 5
Push 4
Stack:
[6, 5, 4]
Step 5:
* operator
5 * 4 = 20
Stack:
[6, 20]
Step 6:
+ operator
6 + 20 = 26
Stack:
[26]
Step 7:
Push 9
Stack:
[26, 9]
Step 8:
- operator
26 - 9 = 17
Final Output:
17
Practice :