LC150 - Evaluate Reverse Polish Notation

Problem

You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.

Evaluate the expression. Return an integer that represents the value of the expression.

Note that:

  • The valid operators are '+', '-', '*', and '/'.

  • Each operand may be an integer or another expression.

  • The division between two integers always truncates toward zero.

  • There will not be any division by zero.

  • The input represents a valid arithmetic expression in a reverse polish notation.

  • The answer and all the intermediate calculations can be represented in a 32-bit integer.

Example

Input: tokens = ["2","1","+","3","*"]

Output: 9

Explanation: ((2 + 1) * 3) = 9

Solution

Use a stack to hold tokens as we parse through the list of tokens. When an operation is encountered, pop two elements from the stack and run the operation. Order of operands matter for division and subtraction. Since we're popping from the end of the stack, the order is reversed. Use temporary variables to hold the popped values and flip them for the calculation.

Time complexity is O(n)O(n) and space complexity is an additional O(n)O(n) of stack space at worst.

def evalRPN(self, tokens: List[str]) -> int:
	ops = {'+', '-', '*', '/'}
	stack = []
	
	for token in tokens:
	
		if token not in ops:
			stack.append(int(token))
		
		else:
			if token == '+':
				stack.append(stack.pop() + stack.pop())
			
			elif token == '-':
				a, b = stack.pop(), stack.pop()
				stack.append(b - a)
			
			elif token == '*':
				stack.append(stack.pop() * stack.pop())
			
			elif token == '/':
				a, b = stack.pop(), stack.pop()
				stack.append(int(b / a))

	return stack[0]

Last updated