InternDoor

Work out a postfix expression

Mediumstack · math

Reported in interviews at (where)

tokens is an arithmetic expression written in postfix order, also called reverse Polish notation: each operator comes right after the two values it works on, so 3 4 + 2 * means (3 + 4) * 2.

The operators are +, -, * and /. Division keeps only the whole part of the answer, cutting towards zero, so 7 / 2 is 3 and 7 / -2 is -3.

Return the value of the expression.

Example 1
Input
tokens = ["6","2","3","-","*","4","/"]
Output
-1

2 - 3 is -1, times 6 is -6, and -6 / 4 is -1.5, which cuts towards zero to -1.

Example 2
Input
tokens = ["9","-2","/"]
Output
-4

9 / -2 is -4.5, so the answer is -4, not -5.

Example 3
Input
tokens = ["42"]
Output
42

A single number is its own value.

Limits

  • 1 <= tokens.length <= 10001
  • each token is an operator or a whole number from -1000 to 1000
  • the expression is valid and never divides by zero
  • every value along the way fits in a 32-bit signed integer

Hints

Hint 1

Push numbers onto a stack. On an operator, pop two values, work it out and push the result.

Hint 2

The first value popped is the right-hand one: for a - b and a / b, pop b, then a.

Where this was reported

Our own problem on the task these candidates describe; the wording, examples and tests are InternDoor’s.

Run your code to check it on the examples. Submit runs every hidden test.

Ready for the real one?

Engineering internships and entry-level jobs in India, newest first.