def isValid(s: str) -> bool:
stack = []
pairs = {')': '(', '}': '{', ']': '['}
for c in s:
if c in pairs:
if not stack or stack.pop() != pairs[c]:
return False
else:
stack.append(c)
return not stack
Queue Using Stacks
// Java — Two stacks
class MyQueue {
Stack<Integer> in = new Stack<>();
Stack<Integer> out = new Stack<>();
public void push(int x) { in.push(x); }
public int pop() {
if (out.isEmpty()) transfer();
return out.pop();
}
public int peek() {
if (out.isEmpty()) transfer();
return out.peek();
}
private void transfer() {
while (!in.isEmpty()) out.push(in.pop());
}
}
Next Greater Element
def nextGreaterElement(nums):
stack, result = [], [-1] * len(nums)
for i in range(len(nums)):
while stack and nums[i] > nums[stack[-1]]:
result[stack.pop()] = nums[i]
stack.append(i)
return result
More Problems
Problem
Pattern
Complexity
Backspace String Compare
Stack simulation, two pointers
O(n), O(n)
Min Stack
Two stacks (values + mins)
O(1) per op
Decode String
Stack for counts and strings
O(n), O(n)
Daily Temperatures
Monotonic decreasing stack
O(n), O(n)
✏️ Exercise: Implement Valid Parentheses with all bracket types, then build a Min Stack class with O(1) getMin(). Solve Backspace Compare with O(n) time.