FastPrepEvaluate a Postfix Expression

Evaluate a Postfix Expression

Google logoGoogle● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Evaluate a valid arithmetic expression written in postfix notation. The input is an array of tokens read from left to right. An integer token contributes a value; an operator consumes the two most recent values. The earlier value is the left operand and the later value is the right operand.

The binary operators are +, -, *, and /. Division truncates toward zero. Return the final integer value.

Function

evaluatePostfix(tokens: String[]) → int

Examples

Example 1

tokens = ["2","3","+","4","*"]return = 20

Add 2 and 3, then multiply the sum by 4.

Example 2

tokens = ["7","-3","/"]return = -2

Seven divided by negative three truncates toward zero.

Example 3

tokens = ["5","1","2","+","4","*","+","3","-"]return = 14

The expression is 5 + (1 + 2) * 4 - 3.

Constraints

  • 1 <= tokens.length <= 10000.
  • Each token is a signed integer in [-200, 200] or one of +, -, *, and /.
  • The tokens form a valid postfix expression, and no division has a zero divisor.
  • Every intermediate result fits in a signed 32-bit integer.

More Google problems

See Google hiring insights
public int evaluatePostfix(String[] tokens) {
    // Write your code here.
}
tokens["2","3","+","4","*"]
expected20
Checking account…