Typorithm · medium

Evaluate RPN

evaluate-rpnstacks-queuespostfixoperand-stackorder
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Evaluate RPN

0%

Stacks & Queues

Push numbers; on an operator, pop two operands (right first), apply, and push the result.

Reverse Polish Notation places operators after their operands, so no parentheses are needed.

A stack holds operands; an operator pops the top two and pushes the result.

Order matters: the top of the stack is the right operand, popped first.

01

Numbers push directly.

02

Operators pop two (right first).

03

Push the computed result back.

function evalRPN(tokens) {
  const stack = [];
  const ops = {
    "+": (a, b) => a + b,
    "-": (a, b) => a - b,
    "*": (a, b) => a * b,
    "/": (a, b) => Math.trunc(a / b),
  };

  for (const token of tokens) {
    if (token in ops) {
      const b = stack.pop();
      const a = stack.pop();
      stack.push(ops[token](a, b));
    } else {
      stack.push(Number(token));
    }
  }

  return stack.pop();
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Operator table

Map each operator to a function; truncate division toward zero.

"/": (a, b) => Math.trunc(a / b)

2. Pop second operand

The right operand is on top, so it pops first.

const b = stack.pop()

3. Pop first operand

The left operand pops second.

const a = stack.pop()

4. Push result

The computed value becomes a new operand.

stack.push(ops[token](a, b))

5. Push operand

Numbers go straight onto the stack.

stack.push(Number(token))

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Evaluate RPN: Lesson & Practice · Typorithm | ApplyDjinn