#150
Evaluate Reverse Polish Notation
MediumArrayMathStackStackArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a stack to evaluate the expression in a single pass. This approach is efficient because it processes each token exactly once, making it linear in time complexity.
⚙️
Algorithm
5 steps- 1Step 1: Initialize an empty stack.
- 2Step 2: Iterate through each token in the input array.
- 3Step 3: If the token is a number, push it onto the stack.
- 4Step 4: If the token is an operator, pop the top two numbers from the stack, apply the operator, and push the result back onto the stack.
- 5Step 5: At the end, the stack will contain one element, which is the result.
solution.py19 lines
1# Full working Python code
2
3def evalRPN(tokens):
4 stack = []
5 for token in tokens:
6 if token not in ['+', '-', '*', '/']:
7 stack.append(int(token))
8 else:
9 b = stack.pop()
10 a = stack.pop()
11 if token == '+':
12 stack.append(a + b)
13 elif token == '-':
14 stack.append(a - b)
15 elif token == '*':
16 stack.append(a * b)
17 elif token == '/':
18 stack.append(int(a / b)) # Truncate towards zero
19 return stack[0]ℹ
Complexity note: This complexity is linear because we process each token exactly once, and the stack operations (push/pop) are O(1).
- 1Using a stack is essential for evaluating expressions in Reverse Polish Notation.
- 2Operators are applied immediately after their operands are available.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.