Stack Blind75
Stack Blind75
Valid Parentheses
Problem: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input
string is valid.
Solution:
bool isValid(string s) {
stack<char> st;
for (char c : s) {
if (c == '(' || c == '{' || c == '[') {
st.push(c);
} else {
if (st.empty()) return false;
char top = st.top();
if ((c == ')' && top != '(') ||
(c == '}' && top != '{') ||
(c == ']' && top != '[')) return false;
st.pop();
}
}
return st.empty();
}
Note: We use a stack to match the most recent opening bracket with the current closing bracket.
Min Stack
Problem: Design a stack that supports push, pop, top, and retrieving the minimum element in
constant time.
Solution:
class MinStack {
stack<int> s, min_s;
public:
void push(int val) {
s.push(val);
if (min_s.empty() || val <= min_s.top())
min_s.push(val);
}
void pop() {
if (s.top() == min_s.top()) min_s.pop();
s.pop();
}
Generate Parentheses
Problem: Given n pairs of parentheses, write a function to generate all combinations of well-formed
parentheses.
Solution:
void backtrack(int open, int close, string str, vector<string>& res) {
if (open == 0 && close == 0) {
res.push_back(str);
return;
}
if (open > 0) backtrack(open - 1, close, str + '(', res);
if (close > open) backtrack(open, close - 1, str + ')', res);
}
vector<string> generateParenthesis(int n) {
vector<string> res;
backtrack(n, n, "", res);
return res;
}
Note: We use backtracking to build valid strings of parentheses recursively.
Daily Temperatures
Problem: Given a list of daily temperatures, return a list such that for each day, tells you how many
days to wait for a warmer temperature.
Solution:
vector<int> dailyTemperatures(vector<int>& T) {
stack<int> st;
vector<int> res(T.size(), 0);
for (int i = 0; i < T.size(); ++i) {
while (!st.empty() && T[i] > T[st.top()]) {
int idx = st.top(); st.pop();
res[idx] = i - idx;
}
st.push(i);
}
return res;
}
Note: A stack stores indices. For each temp, pop all colder previous temps to calculate wait days.
Car Fleet
Problem: There are N cars going to the same destination. Each car travels at different speeds. A car
fleet is formed when slower cars are caught up by faster cars. Return the number of car fleets.
Solution:
int carFleet(int target, vector<int>& pos, vector<int>& speed) {
vector<pair<int, double>> cars;
for (int i = 0; i < pos.size(); ++i)
cars.push_back({pos[i], (double)(target - pos[i]) / speed[i]});
sort(cars.rbegin(), cars.rend());
int fleets = 0;
double curr = 0;
for (auto& car : cars) {
if (car.second > curr) {
fleets++;
curr = car.second;
}
}
return fleets;
}
Note: Sort cars by position, simulate from farthest. If a car takes more time than the current fleet, it forms a
new fleet.