Evaluate Postfix Expression Using Stack in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to evaluate a postfix expression changes as the expression gets longer.
How does the number of steps grow when the input expression size increases?
Analyze the time complexity of the following code snippet.
function evaluatePostfix(expression) {
const stack = [];
for (const char of expression) {
if (!isNaN(char) && char !== ' ') {
stack.push(Number(char));
} else {
const b = stack.pop();
const a = stack.pop();
if (char === '+') stack.push(a + b);
else if (char === '-') stack.push(a - b);
else if (char === '*') stack.push(a * b);
else if (char === '/') stack.push(a / b);
}
}
return stack.pop();
}
This code evaluates a postfix expression by scanning each character, pushing numbers onto a stack, and applying operators to the top two numbers.
- Primary operation: Looping through each character in the expression once.
- How many times: Exactly once for each character in the input expression.
Each character is processed once, so the total steps grow directly with the expression length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 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 directly with the length of the postfix expression.
[X] Wrong: "Since there are nested operations inside the loop, the time complexity must be quadratic."
[OK] Correct: Each character is processed once, and stack operations are constant time, so no nested loops cause repeated full scans.
Understanding this helps you explain how stack-based algorithms handle expressions efficiently, a common skill in coding interviews.
"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 using a stack to hold operands until an operator is encountered.Step 2: Identify the correct data structure
The stack allows pushing operands and popping them for operations, which fits postfix evaluation perfectly.Final Answer:
Stack -> Option CQuick Check:
Postfix evaluation uses stack = Stack [OK]
- Choosing queue instead of stack
- Using array without stack operations
- Confusing with infix evaluation
Solution
Step 1: Recall JavaScript stack operations
JavaScript arrays use push() to add elements to the end, simulating stack push.Step 2: Match correct method
push() is the standard method; add(), insert(), enqueue() are incorrect for stack push.Final Answer:
stack.push(element); -> Option AQuick Check:
Push uses push() method = stack.push(element); [OK]
- Using add() or insert() which don't exist
- Confusing enqueue() with queue operation
- Using pop() instead of push()
"23+5*"?
function evaluatePostfix(expr) {
const stack = [];
for (const ch of expr) {
if (!isNaN(ch)) {
stack.push(Number(ch));
} else {
const b = stack.pop();
const a = stack.pop();
if (ch === '+') stack.push(a + b);
else if (ch === '*') stack.push(a * b);
}
}
return stack.pop();
}
console.log(evaluatePostfix("23+5*"));Solution
Step 1: Evaluate postfix expression "23+5*" step-by-step
Push 2, push 3, then '+' operator: pop 3 and 2, add = 5, push 5. Push 5, then '*' operator: pop 5 and 5, multiply = 25, push 25.Step 2: Final stack value
Only one value 25 remains, which is returned and printed.Final Answer:
25 -> Option AQuick Check:
2+3=5, 5*5=25 = 25 [OK]
- Mixing operand order in subtraction/division
- Forgetting to convert char to number
- Confusing operator precedence
function evalPostfix(expr) {
const stack = [];
for (const ch of expr) {
if (ch >= '0' && ch <= '9') {
stack.push(ch);
} else {
const b = stack.pop();
const a = stack.pop();
if (ch === '+') stack.push(a + b);
else if (ch === '-') stack.push(a - b);
}
}
return stack.pop();
}Solution
Step 1: Check how operands are pushed
The code pushes characters directly without converting to numbers, so operands are strings.Step 2: Effect of pushing strings on arithmetic
Adding strings with '+' concatenates instead of numeric addition, causing wrong results.Final Answer:
Operands are pushed as strings, not numbers -> Option BQuick Check:
Push operands as numbers, not strings = Operands are pushed as strings, not numbers [OK]
- Pushing chars without Number()
- Ignoring operator cases
- Assuming pop order is wrong
"82/3-4*", what is the correct evaluation result using a stack-based approach?Solution
Step 1: Evaluate "82/3-4*" step-by-step
Push 8, push 2, '/' operator: 8 / 2 = 4, push 4. Push 3, '-' operator: 4 - 3 = 1, push 1. Push 4, '*' operator: 1 * 4 = 4, push 4.Step 2: Final stack value
Only one value 4 remains, but check carefully: The last '*' uses 1 and 4, result 4.Step 3: Re-check calculation
Actually, after '-' operation, stack has 1. Then push 4, then '*': 1 * 4 = 4.Final Answer:
4 -> Option DQuick Check:
8/2=4, 4-3=1, 1*4=4 = 4 [OK]
- Mixing operand order in division
- Skipping operator precedence
- Incorrect stack pop sequence
Ready to prove it?
Pass the test and this pattern moves unknown
