150. Evaluate Reverse Polish Notation
Asked at 19Bloomberg48Amazon47Microsoft38Google37Meta34Apple30Citadel78tcs42Apollo.io100Citigroup81Canonical80Grammarly67Anduril55Tesla52LinkedIn51Yandex36Infosys30Oracle27Goldman Sachs21
Problem
Evaluate an arithmetic expression given in Reverse Polish (postfix) notation as a list of tokens: integers and the operators + - * /. Division truncates toward zero. The expression is always valid.
Example: ["2","1","+","3","*"] → 9 (= (2 + 1) × 3)
Push numbers; an operator pops b then a and pushes a op b. Division truncates toward zero.
Complexity: O(n).
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
st = []
for t in tokens:
if t in "+-*/":
b, a = st.pop(), st.pop()
if t == "+": st.append(a + b)
elif t == "-": st.append(a - b)
elif t == "*": st.append(a * b)
else: st.append(int(a / b)) # truncate toward 0
else:
st.append(int(t))
return st[0]
assert Solution().evalRPN(["2", "1", "+", "3", "*"]) == 9
assert Solution().evalRPN(["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]) == 22
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> st = new ArrayDeque<>();
for (String t : tokens) {
switch (t) {
case "+": st.push(st.pop() + st.pop()); break;
case "-": { int b = st.pop(), a = st.pop(); st.push(a - b); break; }
case "*": st.push(st.pop() * st.pop()); break;
case "/": { int b = st.pop(), a = st.pop(); st.push(a / b); break; }
default: st.push(Integer.parseInt(t));
}
}
return st.pop();
}
}
func evalRPN(tokens []string) int {
st := []int{}
for _, t := range tokens {
if len(t) == 1 && strings.Contains("+-*/", t) {
b, a := st[len(st)-1], st[len(st)-2]
st = st[:len(st)-2]
switch t {
case "+":
st = append(st, a+b)
case "-":
st = append(st, a-b)
case "*":
st = append(st, a*b)
default:
st = append(st, a/b) // Go's / truncates toward 0, as required
}
} else {
n, _ := strconv.Atoi(t)
st = append(st, n)
}
}
return st[0]
}