🧠
Optimized Iterative with Inline Operator Function
💡 This approach improves code readability and maintainability by using a map/dictionary for operators, reducing repetitive code.
Intuition
Use a dictionary to map operators to their corresponding lambda functions, then apply them dynamically during iteration.
Algorithm
- Create a dictionary mapping operators to their functions.
- Initialize an empty stack.
- Iterate over tokens, pushing numbers or applying operator functions.
- Pop two operands when operator is encountered, apply function, and push result.
- Return the last element on the stack as the result.
💡 This approach is functionally the same as the previous stack method but improves code elegance and reduces bugs.
class Solution:
def evalRPN(self, tokens):
import operator
ops = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': lambda x, y: int(x / y),
}
stack = []
for token in tokens:
if token in ops:
right = stack.pop()
left = stack.pop()
stack.append(ops[token](left, right))
else:
stack.append(int(token))
return stack.pop()
# Driver code
if __name__ == '__main__':
sol = Solution()
print(sol.evalRPN(["2", "1", "+", "3", "*"])) # Output: 9
Line Notes
import operatorImport standard operator functions for clarity
ops = { ... }Map operators to their corresponding functions
if token in ops:Check if token is an operator
stack.append(ops[token](left, right))Apply operator function dynamically
stack.append(int(token))Push number tokens as integers
import java.util.*;
import java.util.function.BiFunction;
public class Solution {
public int evalRPN(String[] tokens) {
Map<String, BiFunction<Integer, Integer, Integer>> ops = new HashMap<>();
ops.put("+", (a, b) -> a + b);
ops.put("-", (a, b) -> a - b);
ops.put("*", (a, b) -> a * b);
ops.put("/", (a, b) -> a / b);
Deque<Integer> stack = new ArrayDeque<>();
for (String token : tokens) {
if (ops.containsKey(token)) {
int right = stack.pop();
int left = stack.pop();
stack.push(ops.get(token).apply(left, right));
} else {
stack.push(Integer.parseInt(token));
}
}
return stack.pop();
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.evalRPN(new String[]{"2", "1", "+", "3", "*"})); // 9
}
}
Line Notes
Map<String, BiFunction<Integer, Integer, Integer>> ops = new HashMap<>();Map operators to lambda functions for cleaner code
ops.put("+", (a, b) -> a + b);Define addition operator function
if (ops.containsKey(token))Check if token is an operator
stack.push(ops.get(token).apply(left, right));Apply operator function dynamically
stack.push(Integer.parseInt(token));Push number tokens as integers
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <unordered_map>
#include <functional>
using namespace std;
class Solution {
public:
int evalRPN(vector<string>& tokens) {
unordered_map<string, function<int(int,int)>> ops = {
{"+", [](int a, int b) { return a + b; }},
{"-", [](int a, int b) { return a - b; }},
{"*", [](int a, int b) { return a * b; }},
{"/", [](int a, int b) { return a / b; }}
};
stack<int> st;
for (auto& token : tokens) {
if (ops.count(token)) {
int right = st.top(); st.pop();
int left = st.top(); st.pop();
st.push(ops[token](left, right));
} else {
st.push(stoi(token));
}
}
return st.top();
}
};
int main() {
Solution sol;
vector<string> tokens = {"2", "1", "+", "3", "*"};
cout << sol.evalRPN(tokens) << endl; // Output: 9
return 0;
}
Line Notes
unordered_map<string, function<int(int,int)>> ops = { ... };Map operators to lambda functions for clarity
if (ops.count(token))Check if token is an operator
int right = st.top(); st.pop();Pop right operand
st.push(ops[token](left, right));Apply operator function dynamically
st.push(stoi(token));Push number tokens as integers
var evalRPN = function(tokens) {
const ops = {
'+': (a, b) => a + b,
'-': (a, b) => a - b,
'*': (a, b) => a * b,
'/': (a, b) => (a / b) | 0 // truncate toward zero
};
const stack = [];
for (const token of tokens) {
if (token in ops) {
const right = stack.pop();
const left = stack.pop();
stack.push(ops[token](left, right));
} else {
stack.push(parseInt(token));
}
}
return stack.pop();
};
// Test
console.log(evalRPN(["2", "1", "+", "3", "*"])) // 9
Line Notes
const ops = { ... };Map operators to arrow functions for cleaner code
if (token in ops)Check if token is an operator
const right = stack.pop();Pop right operand
stack.push(ops[token](left, right));Apply operator function dynamically
stack.push(parseInt(token));Push number tokens as integers
Same as previous stack approach but with cleaner code structure.
💡 This approach is just as efficient but easier to maintain and less error-prone.
Interview Verdict: Accepted and recommended for clean code
This approach is ideal for interviews where clean, maintainable code is valued.