Evaluating a postfix expression — Aptitude Question
Evaluating a postfix expression: Evaluate the postfix expression 5 6 2 + * 12 4 / - using the usual stack method. Answer and worked solution on CodeKairo.
- Topic: Data Structures & Algorithms
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 90 seconds
Question
Evaluate the postfix expression 5 6 2 + * 12 4 / - using the usual stack method.
Options
- 33
- 37
- 40
- 43
Show the answer and the worked solution
Correct answer: B. 37
Worked solution
- Push 5, 6 and 2 onto the stack.
+pops 2 and 6, computing 6 + 2 = 8. The stack holds 5, 8.*pops 8 and 5, computing 5 × 8 = 40. The stack holds 40.- Push 12 and 4;
/pops 4 and 12, computing 12 ÷ 4 = 3. The stack holds 40, 3. -pops 3 and 40, computing 40 − 3 = 37.
Answer: 37.
The idea
Postfix needs no brackets because the operator arrives after both of its operands. One left-to-right scan with a stack evaluates it, and the order of popping matters for the non-commutative operators.
Shortcut. Rebuild the infix as it is read: 5 × (6 + 2) − 12 ÷ 4 = 40 − 3 = 37.
Common trap. 40 is the value left on the stack after the *, chosen by stopping when the stack first shrinks to one item and ignoring the 12 4 / − still to come.
All Data Structures & Algorithms questions · placement mock tests