Skip to main content

Problem solving Techniques

use static unordered_set<...> varName = { ... } and along with find() to find if that element is present or not

static unordered_set<string> ops = {"+", "-", "*", "/"};

class Solution {
public:
int RPN_Postfix_to_Int(vector<string>& tokens) {
stack<int> stack;
for (auto t : tokens) {
if (ops.find(t) == ops.end()) {
stack.push(stoi(t));
}
else {
int b = stack.top(); stack.pop();
int a = stack.top(); stack.pop();
if (t == "+") stack.push(a + b);
else if (t == "-") stack.push(a - b);
else if (t == "*") stack.push(a * b);
else stack.push(a / b);
}
}
return stack.top();
}
};

use simple vector or array to store conditions of if

vector<int> v1(3);
vector<int> v2(3);

v1[0] = ...;
v1[1] = ...;
v1[3] = ...;

/*
and so on ...
*/


switch case instead of if

int RPN_Postfix_to_Int(vector<string>& tokens) {
stack<int> stn;
for(auto s:tokens) {
if(s.size()>1 || isdigit(s[0])) stn.push(stoi(s));
else {
auto x2=stn.top(); stn.pop();
auto x1=stn.top(); stn.pop();
switch(s[0]) {
case '+': x1+=x2; break;
case '-': x1-=x2; break;
case '*': x1*=x2; break;
case '/': x1/=x2; break;
}
stn.push(x1);
}
}
return stn.top();
}

use for each loop wherever possible

int RPN_Postfix_to_Int(vector<string>& tokens) {
stack<int> stn;
for(auto s:tokens) {
if(s.size()>1 || isdigit(s[0])) stn.push(stoi(s));
else {
auto x2=stn.top(); stn.pop();
auto x1=stn.top(); stn.pop();
switch(s[0]) {
case '+': x1+=x2; break;
case '-': x1-=x2; break;
case '*': x1*=x2; break;
case '/': x1/=x2; break;
}
stn.push(x1);
}
}
return stn.top();
}

---

### Some Tips

- when given sequences, always take conditions for `return` in :
- empty .. no element
- only 1 element
- always consider **dry coding** your algo with atleast first 2 elements
- the condition provided