DSA · Beginner · Pattern 9 of 11
Stack & Queue
12 problems.
Your progress0%
- 1st Visit
- 0/12
- 2nd Visit
- 0/12
- Revise
- 0/12
About this pattern
A stack is last-in, first-out: the most recent unfinished item is always on top, which makes it the natural tool for matching brackets, evaluating expressions, undoing operations and handling nested structures. A queue is first-in, first-out and models processing in arrival order, simulations and bounded histories; a deque supports both ends.
Signals for a stack include nesting, the most recent unmatched element, or reversing order; signals for a queue include ordering by arrival or keeping only the latest few items. Each element is pushed and popped at most once, so these solutions typically run in O(n) time. In C++, use stack, queue and deque, or a vector used as a stack.
// Stack: match each closing symbol with the most recent opening one.
stack<char> st;
for (char c : s) {
if (isOpening(c)) st.push(c);
else if (!st.empty() && matches(st.top(), c)) st.pop();
else { /* unmatched closing symbol */ }
}
// Queue: process items in arrival order.
queue<int> q;
q.push(first);
while (!q.empty()) {
int cur = q.front(); q.pop();
// handle cur, push any follow-up items
}