AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Mediumstackexpression

~90s

Evaluating a prefix expression

Evaluate the prefix expression + 9 * 3 - 5 2.

Show the answer and the worked solution

Correct answer: D.

18

Worked solution

  1. Scanning right to left, push 2 and then 5.
  2. - pops 5 and 2, computing 5 − 2 = 3. Push 3.
  3. Push the next operand, 3.
  4. * pops 3 and 3, computing 3 × 3 = 9. Push 9.
  5. 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.

Evaluating a prefix expression — Aptitude Question

Evaluating a prefix expression: Evaluate the prefix expression + 9 * 3 - 5 2. Answer and worked solution on CodeKairo.

Question

Evaluate the prefix expression + 9 * 3 - 5 2.

Options

  1. 9
  2. 12
  3. 15
  4. 18
Show the answer and the worked solution

Correct answer: D. 18

Worked solution

  1. Scanning right to left, push 2 and then 5.
  2. - pops 5 and 2, computing 5 − 2 = 3. Push 3.
  3. Push the next operand, 3.
  4. * pops 3 and 3, computing 3 × 3 = 9. Push 9.
  5. 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