1. Recursive Sub-Expression Reduction
Intuition
Repeatedly find the first operator in tokens, evaluate it with its two immediately preceding numbers, replace all 3 tokens with the result, and repeat until 1 token remains.
Algorithm
- Step 1: Loop while
tokens.length > 1. - Step 2: Scan for first index
icontaining an operator (+,-,*,/). - Step 3: Let
a = Number(tokens[i - 2]),b = Number(tokens[i - 1]). - Step 4: Compute
res = evaluate(tokens[i], a, b). - Step 5: Replace
tokens[i-2...i]withresand repeat.
#include <iostream>#include <vector>#include <string> class Solution {public: int evalRPN(std::vector<std::string>& tokens) { while (tokens.size() > 1) { for (size_t i = 0; i < tokens.size(); i++) { if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") { int a = std::stoi(tokens[i - 2]); int b = std::stoi(tokens[i - 1]); int res = 0; if (tokens[i] == "+") res = a + b; else if (tokens[i] == "-") res = a - b; else if (tokens[i] == "*") res = a * b; else if (tokens[i] == "/") res = a / b; tokens.erase(tokens.begin() + i - 2, tokens.begin() + i + 1); tokens.insert(tokens.begin() + i - 2, std::to_string(res)); break; } } } return std::stoi(tokens[0]); }}; int main() { Solution solver; std::vector<std::string> tokens = {"2", "1", "+", "3", "*"}; std::cout << "Result: " << solver.evalRPN(tokens) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Repeatedly scans the array to find the first operator, collapses its operands, and splices the array, taking O(N) per operation across O(N) operators. - Space complexity:
O(N)— O(N) space for intermediate arrays.
Why Brute Force Doesn't Scale:
For 104 tokens, O(N2) creates 108 shifting operations.
Stack approach evaluates 10,000 tokens in ~2ms.