Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Stack

Evaluate reverse Polish notation

Medium · Target 15 minutes · Stack· Type asked at

You're given a string expr holding an arithmetic expression in reverse Polish notation, with the tokens separated by single spaces. Each token is an integer or one of + - * /, and an operator applies to the two values before it. Return the value of the expression.

Division between two integers truncates towards zero, so -7 2 / is -3. The expression is always valid, it never divides by zero, and every intermediate value fits in a 32-bit signed integer.

Examples

InputOutputWhy
expr = "2 1 + 3 *"9(2 + 1) × 3.
expr = "4 13 5 / +"613 / 5 truncates to 2, and 4 + 2 = 6.
expr = "-7 2 /"-3Truncated towards zero, not rounded down to −4.

Constraints

  • 1 ≤ number of tokens ≤ 10⁴
  • Each integer is between −200 and 200
  • Every intermediate value fits in 32 bits

Hints

Hint 1

Whenever you read an operator, think about which two values it applies to. I'd say they're always the two most recent values that you haven't used up yet.

Hint 2

That suggests keeping the values on a stack, where each number gets pushed and each operator pops two values and pushes its result back on.

Hint 3

Remember that the first value you pop is the right-hand operand, so for 13 5 / you'll pop 5 and then 13 and you want 13 / 5 (which is 2 after truncating).

Where people lose marks

  • Popping the operands in the wrong order is probably the most common mistake I see, because "3 4 -" should give −1 and swapping them gives you 1.
  • Python's // and Haskell's div both round downwards, so -7 // 2 gives −4 when the answer you want is −3. You'd use int(a / b) in Python and quot in Haskell instead.
  • If you check for an operator with something like token[0] == '-' you'll get caught out by negative numbers such as "-3", which also start with a minus sign, so I'd always compare the whole token.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.