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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit