Evaluate Postfix Expression Using Stack in DSA C# - Time & Space Complexity
We want to understand how the time needed to evaluate a postfix expression changes as the expression gets longer.
Specifically, how does the number of steps grow with the size of the input expression?
Analyze the time complexity of the following code snippet.
public int EvaluatePostfix(string expression)
{
Stack<int> stack = new Stack<int>();
foreach (char c in expression)
{
if (char.IsDigit(c))
stack.Push(c - '0');
else
{
int val2 = stack.Pop();
int val1 = stack.Pop();
stack.Push(ApplyOp(val1, val2, c));
}
}
return stack.Pop();
}
private int ApplyOp(int a, int b, char op)
{
switch (op)
{
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
default: return 0;
}
}
This code evaluates a postfix expression by scanning each character, pushing numbers onto a stack, and applying operators to the top two numbers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character in the expression once.
- How many times: Exactly once per character in the input string.
As the expression length grows, the number of steps grows directly with it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps (one per character) |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The work grows in a straight line with input size; doubling input doubles work.
Time Complexity: O(n)
This means the time to evaluate grows linearly with the length of the postfix expression.
[X] Wrong: "Since we pop and push inside the loop, the complexity is more than linear, maybe quadratic."
[OK] Correct: Each character is processed once, and each push/pop is constant time, so total steps still grow linearly.
Understanding this linear time complexity helps you explain how stack-based evaluation is efficient and why it is preferred for postfix expressions.
"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 pushing operands onto a stack and popping them when an operator is encountered. The stack allows last-in, first-out access which is perfect for postfix evaluation.Final Answer:
Stack -> Option CQuick Check:
Postfix evaluation uses stack [OK]
- Confusing stack with queue
- Using array without stack logic
- Thinking linked list is primary structure
stack?Solution
Step 1: Recall C# Stack.Push method
In C#, the method to add an element to a stack isPush.Enqueueis for queues;AddandInsertare not stack methods.Final Answer:
stack.Push(operand); -> Option AQuick Check:
Use Push() to add to stack [OK]
- Using Enqueue which is for queues
- Using Add or Insert which are not stack methods
- Confusing stack with list methods
"23+5*"?
string expr = "23+5*";
Stack<int> stack = new Stack<int>();
foreach (char c in expr)
{
if (char.IsDigit(c))
stack.Push(c - '0');
else
{
int b = stack.Pop();
int a = stack.Pop();
if (c == '+') stack.Push(a + b);
else if (c == '*') stack.Push(a * b);
}
}
Console.WriteLine(stack.Pop());Solution
Step 1: Trace code execution
Push 2, push 3; '+' pops b=3, a=2, push 5. Push 5; '*' pops b=5, a=5, push 25. Final pop prints 25.Final Answer:
25 -> Option AQuick Check:
(2+3)*5 = 25 [OK]
- Mixing operand order when popping
- Confusing '+' and '*' operations
- Forgetting to convert char digits to int
string expr = "82/";
Stack<int> stack = new Stack<int>();
foreach (char c in expr)
{
if (char.IsDigit(c))
stack.Push(c - '0');
else
{
int a = stack.Pop();
int b = stack.Pop();
if (c == '/') stack.Push(b / a);
}
}
Console.WriteLine(stack.Pop());Solution
Step 1: Trace popping and computation for division
Push 8, push 2 (top=2). For '/', b=Pop()=2 (right), a=Pop()=8 (left), but pushes b/a=2/8=0 instead of a/b=8/2=4. Operands popped correctly but used/applied in wrong order for non-commutative division.Final Answer:
Operands are popped in wrong order -> Option BQuick Check:
Pop right first (b), left second (a), compute a / b [OK]
- Swapping operand order causing wrong division
- Not handling division operator
- Forgetting to convert char to int
"6523+8*+3+*", what is the final result after evaluation using a stack?Solution
Step 1: Evaluate postfix step-by-step
Push 6,5,2,3; '+' pops 3&2 push 5 (stack:6,5,5); push 8; '*' pops 8&5 push 40 (6,5,40); '+' pops 40&5 push 45 (6,45); push 3 (6,45,3); '+' pops 3&45 push 48 (6,48); '*' pops 48&6 push 288.Final Answer:
288 -> Option DQuick Check:
Stepwise postfix evaluation = 288 [OK]
- Misordering operands during pop
- Skipping steps in complex expressions
- Confusing operator precedence in postfix
Ready to prove it?
Pass the test and this pattern moves unknown
