Evaluate Reverse Polish Notation

Stack of operands — on operator, pop two, apply, push result.

Medium
Time O(n) Space O(n)
LeetCode
3 min read
stack string parsing

Problem#

Evaluate an arithmetic expression in Reverse Polish Notation. Operators are +, -, *, / (truncated toward zero for division).

Examples#

  • ["2","1","+","3","*"]9 ((2+1)*3).
  • ["4","13","5","/","+"]6.

Constraints#

  • 1 <= tokens.length <= 10^4.

Approach#

Stack. Push every operand. On an operator, pop two, apply (note order: the second pop is the left operand), push the result.

Solution#

Evaluate Reverse Polish Notation
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for (auto& t : tokens) {
if (t == "+" || t == "-" || t == "*" || t == "/") {
int b = st.top(); st.pop();
int a = st.top(); st.pop();
if (t == "+") st.push(a + b);
else if (t == "-") st.push(a - b);
else if (t == "*") st.push(a * b);
else st.push(a / b);
} else st.push(stoi(t));
}
return st.top();
}
};

Editorial#

Order of pops is b (right operand) before a (left operand) — getting this wrong silently produces wrong answers for non-commutative ops. C++ integer division already truncates toward zero, matching the problem’s spec.

Complexity#

  • Time: O(n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.