0% found this document useful (0 votes)
10 views4 pages

Stack Blind75

The document provides solutions to various problems using stack data structures in C++. It includes algorithms for validating parentheses, designing a minimum stack, evaluating expressions in Reverse Polish Notation, generating well-formed parentheses, calculating daily temperature waits, counting car fleets, and finding the largest rectangle in a histogram. Each solution is accompanied by a brief explanation of the approach used.

Uploaded by

leviandlight
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views4 pages

Stack Blind75

The document provides solutions to various problems using stack data structures in C++. It includes algorithms for validating parentheses, designing a minimum stack, evaluating expressions in Reverse Polish Notation, generating well-formed parentheses, calculating daily temperature waits, counting car fleets, and finding the largest rectangle in a histogram. Each solution is accompanied by a brief explanation of the approach used.

Uploaded by

leviandlight
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Stack - Blind 75 (C++)

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();
}

int top() { return s.top(); }

int getMin() { return min_s.top(); }


};
Note: We maintain an auxiliary stack that stores the current minimum element.
Evaluate Reverse Polish Notation
Problem: Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Solution:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for (string& t : tokens) {
if (t == "+" || t == "-" || t == "*" || t == "/") {
int b = st.top(); st.pop();
int a = st.top(); st.pop();
if (t == "+") st.push(a + b);
else if (t == "-") st.push(a - b);
else if (t == "*") st.push(a * b);
else st.push(a / b);
} else {
st.push(stoi(t));
}
}
return st.top();
}
Note: A stack is used to evaluate the operands and apply the operator in postfix order.

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.

Largest Rectangle In Histogram


Problem: Given an array of integers representing the histogram's bar height, return the area of the
largest rectangle.
Solution:
int largestRectangleArea(vector<int>& heights) {
stack<int> st;
heights.push_back(0);
int maxA = 0;
for (int i = 0; i < heights.size(); ++i) {
while (!st.empty() && heights[i] < heights[st.top()]) {
int h = heights[st.top()]; st.pop();
int w = st.empty() ? i : i - st.top() - 1;
maxA = max(maxA, h * w);
}
st.push(i);
}
return maxA;
}
Note: Use a monotonic stack to track increasing bars. Calculate area whenever a lower height appears.

You might also like