LeetCode 150: Evaluate Reverse Polish Notation is a Medium stack problem. This Python walkthrough develops an operand stack solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Stack |
| Reusable pattern | operand stack |
| Complexity | O(n) time and O(n) space |
Recognizing the pattern
A stack is appropriate when the newest unresolved item must be handled before older unresolved items.
For this problem specifically, push numbers and, for each operator, pop the right operand then the left operand, apply the operation, and push the result. The invariant worth writing beside the code is: The stack contains the evaluated values of complete subexpressions in the processed token prefix.
Step-by-step algorithm
- Identify the input state consumed by
evalRPN(tokens)and initialize the data required by the operand stack pattern. - Push numbers and, for each operator, pop the right operand then the left operand, apply the operation, and push the result.
- After each update, verify the page’s central invariant: The stack contains the evaluated values of complete subexpressions in the processed token prefix.
- Finish only after the boundary behavior is covered: Division truncates toward zero and operand order matters for subtraction and division.
Python solution
class Solution:
def evalRPN(self, tokens):
stack = []
for token in tokens:
if token not in {"+", "-", "*", "/"}:
stack.append(int(token))
continue
right, left = stack.pop(), stack.pop()
if token == "+": stack.append(left + right)
elif token == "-": stack.append(left - right)
elif token == "*": stack.append(left * right)
else: stack.append(int(left / right))
return stack[-1]Reading the implementation
The main entry point is evalRPN(tokens). The named working state includes stack, right; those variables make the operand stack state visible instead of hiding it in incidental control flow.
A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. In concrete terms, push numbers and, for each operator, pop the right operand then the left operand, apply the operation, and push the result.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Push numbers and, for each operator, pop the right operand then the left operand, apply the operation, and push the result. Each update records the current item without invalidating earlier decisions; consequently, the stack contains the evaluated values of complete subexpressions in the processed token prefix.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(n) time and O(n) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
Repeated rescanning can find the same dependency without a stack, but it usually hides the nesting invariant and costs more time. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert Solution().evalRPN(["2","1","+","3","*"]) == 9Common mistakes and edge cases
- Problem-specific boundary: Division truncates toward zero and operand order matters for subtraction and division.
- Pattern-level pitfall: Check emptiness before reading the top and decide whether an operator, delimiter, or node is consumed before or after the pop.
- Invariant check: after every update, confirm that the stack contains the evaluated values of complete subexpressions in the processed token prefix.
Interview review checklist
- Explain why operand stack matches the structure of this input.
- State the invariant in one sentence before tracing code: The stack contains the evaluated values of complete subexpressions in the processed token prefix.
- Derive O(n) time and O(n) space from how many times each element or state is visited.
- Test the boundary explicitly: Division truncates toward zero and operand order matters for subtraction and division.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 155. Min Stack · Next: 224. Basic Calculator