Evaluate Postfix Expression Using Stack in DSA C++ - Time & Space Complexity
We want to understand how the time to evaluate a postfix expression changes as the expression gets longer.
Specifically, how many steps does it take to process each symbol in the expression?
Analyze the time complexity of the following code snippet.
int evaluatePostfix(string expr) {
stack<int> s;
for (char c : expr) {
if (isdigit(c)) s.push(c - '0');
else {
int b = s.top(); s.pop();
int a = s.top(); s.pop();
if (c == '+') s.push(a + b);
else if (c == '-') s.push(a - b);
else if (c == '*') s.push(a * b);
else if (c == '/') s.push(a / b);
}
}
return s.top();
}
This code evaluates a postfix expression by scanning each character once and using a stack to store intermediate results.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Single loop over each character in the expression.
- How many times: Exactly once per character in the input string.
Each character is processed once, so the total steps grow directly with the length of the expression.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: Doubling the input doubles the work; growth is linear.
Time Complexity: O(n)
This means the time to evaluate grows in direct proportion to the expression length.
[X] Wrong: "Because we pop and push inside the loop, the time is more than linear, maybe quadratic."
[OK] Correct: Each character is handled once, and stack operations are fast and constant time, so total time stays linear.
Understanding this linear time complexity helps you explain how stack-based evaluation is efficient and practical for expression parsing.
"What if the expression included multi-digit numbers separated by spaces? How would the time complexity change?"
Practice
Solution
Step 1: Understand postfix evaluation process
Postfix expressions are evaluated by scanning from left to right and using a stack to store operands.Step 2: Identify the data structure used
Operands are pushed onto the stack, and when an operator is found, operands are popped for calculation, then the result is pushed back.Final Answer:
Stack -> Option BQuick Check:
Postfix evaluation uses Stack [OK]
- Using queue instead of stack
- Trying to evaluate without any data structure
- Confusing postfix with infix evaluation
Solution
Step 1: Recall C++ stack push syntax
The standard C++ stack uses the member function push() to add elements.Step 2: Match syntax with options
Only s.push(5); uses s.push(5); which is correct syntax.Final Answer:
s.push(5); -> Option DQuick Check:
Stack push syntax = s.push(value) [OK]
- Using non-existent methods like add() or insert()
- Calling push as a free function instead of member function
- Confusing push with pop
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int evaluatePostfix(string exp) {
stack<int> s;
for (char c : exp) {
if (isdigit(c)) {
s.push(c - '0');
} else {
int val2 = s.top(); s.pop();
int val1 = s.top(); s.pop();
switch(c) {
case '+': s.push(val1 + val2); break;
case '-': s.push(val1 - val2); break;
case '*': s.push(val1 * val2); break;
case '/': s.push(val1 / val2); break;
}
}
}
return s.top();
}
int main() {
cout << evaluatePostfix("231*+9-");
return 0;
}Solution
Step 1: Evaluate postfix expression "231*+9-" step-by-step
Push 2, push 3, push 1. '*' operator: pop 1 and 3, multiply 3*1=3, push 3. '+' operator: pop 3 and 2, add 2+3=5, push 5. Push 9. '-' operator: pop 9 and 5, subtract 5-9=-4, push -4.Step 2: Final value on stack is -4
After all operations, the stack top is -4, which is the result printed.Final Answer:
-4 -> Option AQuick Check:
Postfix "231*+9-" = -4 [OK]
- Mixing operand order in subtraction
- Forgetting to convert char digits to int
- Popping operands in wrong order
int evaluatePostfix(string exp) {
stack<int> s;
for (char c : exp) {
if (isdigit(c)) {
s.push(c - '0');
} else {
int val1 = s.top(); s.pop();
int val2 = s.top(); s.pop();
switch(c) {
case '+': s.push(val1 + val2); break;
case '-': s.push(val1 - val2); break;
case '*': s.push(val1 * val2); break;
case '/': s.push(val1 / val2); break;
}
}
}
return s.top();
}Solution
Step 1: Analyze operand popping order
The code pops val1 first, then val2. In postfix evaluation, val2 is the top operand, val1 is below it.Step 2: Correct operand order for operations
Operations should be val1 (second popped) operator val2 (first popped). The code reverses this, causing wrong results.Final Answer:
Operands val1 and val2 are popped in wrong order -> Option CQuick Check:
Operand order matters: val2 = top, val1 = next [OK]
- Swapping operand order in operations
- Not popping operands before using them
- Confusing isdigit() usage
Solution
Step 1: Evaluate postfix "56+82/-" stepwise
Push 5, push 6. '+' operator: pop 6 and 5, add 5+6=11, push 11. Push 8, push 2. '/' operator: pop 2 and 8, divide 8/2=4, push 4. '-' operator: pop 4 and 11, subtract 11-4=7, push 7.Step 2: Final value on stack is 7
After all operations, the stack top is 7, which is the result.Final Answer:
7 -> Option AQuick Check:
Postfix "56+82/-" = 7 [OK]
- Incorrect operand order in division and subtraction
- Misreading the expression characters
- Forgetting to convert char digits to int
Ready to prove it?
Pass the test and this pattern moves unknown
