MEDIUM NC#23 Stack
150. Evaluate Reverse Polish Notation
๐ Problem
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, , and /. Each operand may be an integer or another expression. Note that division between two integers should truncate toward zero. It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
๐ก Approach
- โ Use stack to store operands
- โ When encountering operator, pop two operands and apply operation
- โ Push result back to stack
- โ Final result is only element left in stack
- โ Time: O(n), Space: O(n)
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse stack to store operands
- โขWhen encountering operator, pop two operands and apply operation
- โขPush result back to stack
Common Pitfalls
- โขFinal result is only element left in stack
- โขTime: O(n), Space: O(n)
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
evalRPN(["2","1","+","3","*"]); Expected:
9 Test Case 2
Not run Input:
evalRPN(["4","13","5","/","+"]); Expected:
6 Test Case 3
Not run Input:
evalRPN(["10","6","9","3","+","-11","*","/","*","17","+","5","+"]); Expected:
22 ๐ Code Editor
๐ค Output