Evaluating a prefix expression — Aptitude Question
Evaluating a prefix expression: Evaluate the prefix expression + 9 * 3 - 5 2. Answer and worked solution on CodeKairo.
- Topic: Data Structures & Algorithms
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 90 seconds
Question
Evaluate the prefix expression + 9 * 3 - 5 2.
Options
- 9
- 12
- 15
- 18
Show the answer and the worked solution
Correct answer: D. 18
Worked solution
- Scanning right to left, push 2 and then 5.
-pops 5 and 2, computing 5 − 2 = 3. Push 3.- Push the next operand, 3.
*pops 3 and 3, computing 3 × 3 = 9. Push 9.- Push 9, then
+pops 9 and 9, computing 9 + 9 = 18.
Answer: 18.
The idea
Prefix is postfix read backwards, so the same stack works with the scan reversed and the popping order flipped. The expression is 9 + 3 × (5 − 2).
Shortcut. Evaluate the innermost operator with two numbers after it first: − 5 2 → 3, then * 3 3 → 9, then + 9 9 → 18.
Common trap. 9 is the result of * 3 3, picked by forgetting the leading + that still adds the first 9.
All Data Structures & Algorithms questions · placement mock tests