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

~90s

Evaluating a postfix expression

Evaluate the postfix expression 5 6 2 + * 12 4 / - using the usual stack method.

Show the answer and the worked solution

Correct answer: B.

37

Worked solution

  1. Push 5, 6 and 2 onto the stack.
  2. + pops 2 and 6, computing 6 + 2 = 8. The stack holds 5, 8.
  3. * pops 8 and 5, computing 5 × 8 = 40. The stack holds 40.
  4. Push 12 and 4; / pops 4 and 12, computing 12 ÷ 4 = 3. The stack holds 40, 3.
  5. - 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.

Data Structures & Algorithms

1 of 40

Level

Medium

Target time

~90s

PreviousNext

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.

Question

Evaluate the postfix expression 5 6 2 + * 12 4 / - using the usual stack method.

Options

  1. 33
  2. 37
  3. 40
  4. 43
Show the answer and the worked solution

Correct answer: B. 37

Worked solution

  1. Push 5, 6 and 2 onto the stack.
  2. + pops 2 and 6, computing 6 + 2 = 8. The stack holds 5, 8.
  3. * pops 8 and 5, computing 5 × 8 = 40. The stack holds 40.
  4. Push 12 and 4; / pops 4 and 12, computing 12 ÷ 4 = 3. The stack holds 40, 3.
  5. - 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