Skip to content
We areTOP 1%
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
}

Problems

Stack & Queue questions
#ProblemPlatformDifficultyOpen1st1st Visit2nd2nd VisitRevRevise
1Valid ParenthesesLeetCodeEasy Solve Valid Parentheses on LeetCode (opens in a new tab)
2Implement Queue using StacksLeetCodeEasy Solve Implement Queue using Stacks on LeetCode (opens in a new tab)
3Remove All Adjacent Duplicates In StringLeetCodeEasy Solve Remove All Adjacent Duplicates In String on LeetCode (opens in a new tab)
4Jzzhu and ChildrenCodeforcesEasy 1000Solve Jzzhu and Children on Codeforces (opens in a new tab)
5Move BracketsCodeforcesEasy 1000Solve Move Brackets on Codeforces (opens in a new tab)
6Social Network (easy version)CodeforcesEasy 1000Solve Social Network (easy version) on Codeforces (opens in a new tab)
7YetnotherrokenKeoardCodeforcesEasy 1000Solve YetnotherrokenKeoard on Codeforces (opens in a new tab)
8Even PositionsCodeforcesEasy 1100Solve Even Positions on Codeforces (opens in a new tab)
9Min StackLeetCodeMedium Solve Min Stack on LeetCode (opens in a new tab)
10Evaluate Reverse Polish NotationLeetCodeMedium Solve Evaluate Reverse Polish Notation on LeetCode (opens in a new tab)
11Asteroid CollisionLeetCodeMedium Solve Asteroid Collision on LeetCode (opens in a new tab)
12Decode StringLeetCodeMedium Solve Decode String on LeetCode (opens in a new tab)

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account