Stack · Pattern 1 of 1
Stack problems: match, cancel, evaluate, nest
Push what is still open or pending; when the next item resolves it, pop. Brackets, cancelling neighbours, calculators and nested decoding are all this one move.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Valid brackets or the minimum fix to make them valid
- Neighbours that cancel or collide
- Evaluate an expression with + − × ÷ and parentheses
- Nested structures like 3[a2[c]] or a file path
The template
boolean isValid(String s) {
Deque<Character> st = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c == '(') st.push(')'); // push the closer we expect
else if (c == '[') st.push(']');
else if (c == '{') st.push('}');
else if (st.isEmpty() || st.pop() != c) return false;
}
return st.isEmpty(); // nothing left open
}
int evalRPN(String[] tokens) {
Deque<Integer> st = new ArrayDeque<>();
for (String t : tokens) {
if ("+-*/".contains(t) && t.length() == 1) {
int b = st.pop(), a = st.pop(); // second pop is the left operand
st.push(t.equals("+") ? a + b : t.equals("-") ? a - b : t.equals("*") ? a * b : a / b);
} else st.push(Integer.parseInt(t));
}
return st.pop();
} def is_valid(s):
pairs = {')': '(', ']': '[', '}': '{'}
st = []
for c in s:
if c in pairs:
if not st or st.pop() != pairs[c]:
return False
else:
st.append(c)
return not st # nothing left open
def eval_rpn(tokens):
st = []
for t in tokens:
if t in ('+', '-', '*', '/'):
b, a = st.pop(), st.pop() # second pop is the left operand
st.append(a + b if t == '+' else a - b if t == '-' else a * b if t == '*' else int(a / b))
else:
st.append(int(t))
return st.pop() bool isValid(string s) {
stack<char> st;
for (char c : s) {
if (c == '(') st.push(')'); // push the closer we expect
else if (c == '[') st.push(']');
else if (c == '{') st.push('}');
else { if (st.empty() || st.top() != c) return false; st.pop(); }
}
return st.empty(); // nothing left open
}
int evalRPN(vector<string>& tokens) {
stack<int> st;
for (auto& t : tokens) {
if (t == "+" || t == "-" || t == "*" || t == "/") {
int b = st.top(); st.pop();
int a = st.top(); st.pop(); // second pop is the left operand
st.push(t == "+" ? a + b : t == "-" ? a - b : t == "*" ? a * b : a / b);
} else st.push(stoi(t));
}
return st.top();
} function isValid(s) {
const close = { '(': ')', '[': ']', '{': '}' };
const st = [];
for (const c of s) {
if (c in close) st.push(close[c]); // push the closer we expect
else if (st.pop() !== c) return false;
}
return st.length === 0; // nothing left open
}
function evalRPN(tokens) {
const st = [];
for (const t of tokens) {
if (['+', '-', '*', '/'].includes(t)) {
const b = st.pop(), a = st.pop(); // second pop is the left operand
st.push(t === '+' ? a + b : t === '-' ? a - b : t === '*' ? a * b : Math.trunc(a / b));
} else st.push(Number(t));
}
return st.pop();
} The variations
-
1Match and fix brackets
Push openers (or the closer you expect); a closer must match the top. To fix a string, push indexes and delete whatever is left unmatched. With
*wildcards, track a range of possible open counts. -
2Cancel or collide with the top
Compare each new item with the top: equal letters cancel, asteroids moving toward each other collide, "C" removes the last score. Keep counts on the stack for "k adjacent".
-
3Evaluate expressions
Postfix: numbers go on the stack, an operator pops two. Infix: push signed numbers, apply × and ÷ to the top at once, recurse (or push state) at each parenthesis, sum at the end.
Now you solve -
4Nesting
On "[" (or a start event) push the current state and begin a new one; on "]" pop and combine. Paths, nested lists and function timelines nest the same way.
Now you solve- Simplify Path Medium Stuck? solution
- Exclusive Time of Functions Medium Stuck? solution
- Mini Parser Medium Stuck? solution
-
5Design with stacks
A min stack stores the minimum alongside each value. Two stacks make a queue (move items only when the output stack is empty); a queue rotated after each push makes a stack.
Now you solve -
6More practice
More problems that use this pattern. Try them once the variations above feel easy.
Problems
Mistakes to avoid
- Python
//floors negative numbers (−7 // 2 = −4); RPN wants truncation, so useint(a / b). - Pushing indexes vs characters: push indexes when you must delete or measure later.
- Calculators: applying
*and/before+and−needs either two stacks or "push signed numbers, collapse * and / immediately".
Lesson done
Back to Stack →Mark it done once you can write the template from memory and you have solved the worked examples yourself.