Kodewick
Start learning →
Patterns: stacks and queues17 / 52

Patterns: stacks and queues

Lesson 17 of 52 · Part 3 · Stacks and queues · about 20 minutes

This review of stacks and queues gives a pattern for each of the three classic problems: is a pop order possible, a queue built from two stacks, and a monotonic stack for the next greater number, by hand and then with std::stack.

Stacks and queues aren't hard in themselves; the hard part is seeing which one a problem needs, and how. The three kinds of problem in this lesson (plus circular-queue sums) come up again and again in finals, postgraduate entrance exams and interviews; learn one pattern for each.

Pattern 1: is a pop order possible

The first lesson worked it out by hand: with push order 1 2 3, the pop order 3 1 2 is impossible. As a program, you just act it out: push in order, and after each push, while the top is the next number that should come out, pop it. If the stack ends up empty, the pop order can be done.

stack

Pushed in the order 1 2 3, wanted out as 3 1 2: just try it
main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5// the push order is 1, 2, …, n; out is the pop order we want6bool valid(const vector<int>& out) {7    int n = out.size();8    int st[100], t = -1, k = 0;9    for (int x = 1; x <= n; x++) {10        st[++t] = x;11        while (t >= 0 && st[t] == out[k]) {12            t--;13            k++;14        }15    }16    return t == -1;17}18 19int main() {20    vector<vector<int>> tests = {{3, 2, 1}, {3, 1, 2}, {2, 4, 3, 1}, {4, 1, 2, 3}};21    for (const vector<int>& p : tests) {22        for (int x : p)23            cout << x << " ";24        cout << (valid(p) ? "yes" : "no") << "\n";25    }26    return 0;27}
Output
3 2 1 yes
3 1 2 no
2 4 3 1 yes
4 1 2 3 no

Each number goes in at most once and comes out at most once: O(n).

Choose one

Pushed in the order 1 2 3 4 5, which of these cannot be the pop order?

Exercise 1

Check a pop order

Fill in valid: the push order is 1 to n; decide whether out can be the pop order.

It should print
1 0 1
exercise1.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5bool valid(const vector<int>& out) {6    int n = out.size();7    int st[100], t = -1, k = 0;8    for (int x = 1; x <= n; x++) {9        // push x; while the top equals out[k], pop and k++10    }11    return t == -1;12}13 14int main() {15    cout << valid({1, 3, 2}) << " " << valid({3, 1, 2}) << " " << valid({4, 3, 5, 2, 1}) << "\n";16    return 0;17}
Output
Press Run or Ctrl+Enter

Pattern 2: a queue from two stacks

A classic interview question: with only stacks, how do you get first in, first out? Use two: in only takes things in, out only gives them out. To dequeue when out is empty, pour everything from in into out: pouring reverses the order, so the earliest arrival lands on top of out.

in

out

A queue from two stacks: 1 2 3 went into in; at a dequeue out is empty, so in is poured over and the earliest, 1, is on top of out
main.cpp
1#include <iostream>2using namespace std;3 4class TwoStackQueue {5    int in[100], out[100];6    int tin = -1, tout = -1;               // the two stacks' top indexes7public:8    void enqueue(int x) {9        in[++tin] = x;10    }11    int dequeue() {12        if (tout == -1)                    // pour only when out is empty13            while (tin >= 0)14                out[++tout] = in[tin--];15        return out[tout--];16    }17};18 19int main() {20    TwoStackQueue q;21    q.enqueue(1);22    q.enqueue(2);23    q.enqueue(3);24    cout << q.dequeue() << " ";25    q.enqueue(4);26    cout << q.dequeue() << " ";27    cout << q.dequeue() << " ";28    cout << q.dequeue() << "\n";29    return 0;30}
Output
1 2 3 4

The key is to pour only when out is empty: pour while out still holds something and the new ones land on top of the old ones, scrambling the order. Each element is poured only once in its life, so although one dequeue may pour many, on average each one is O(1) (amortised, the same idea as a vector doubling its capacity).

Choose one

in holds 1 2 3 from bottom to top, and out is empty. After one dequeue, what does out hold from bottom to top?

Exercise 2

A queue from two stacks

Fill in pop: only when out is empty, pour all of in over, then take from out.

It should print
5 6 7
exercise2.cpp
1#include <iostream>2#include <stack>3using namespace std;4 5class MyQueue {6    stack<int> in, out;7public:8    void push(int x) { in.push(x); }9    int pop() {10        // out empty: take in's elements one by one and push them onto out11        if (out.empty()) return -1;   // still empty after pouring: the queue is empty12        int x = out.top();13        out.pop();14        return x;15    }16};17 18int main() {19    MyQueue q;20    q.push(5);21    q.push(6);22    cout << q.pop() << " ";23    q.push(7);24    cout << q.pop() << " ";25    cout << q.pop() << "\n";26    return 0;27}
Output
Press Run or Ctrl+Enter

Pattern 3: the monotonic stack, the next greater number

The problem: for each number, find the first number to its right that is greater, or −1 if there is none. Two nested loops are O(n²). The pattern is a monotonic stack: the stack holds the indexes of numbers still waiting for their answer, decreasing from bottom to top. When a new number arrives that's greater than the top, it is the top's answer: pop; repeat until the top isn't smaller, then push the new one.

a2153401234↑i
st (indexes on the stack, bottom on the left)

A monotonic stack for "the next greater number" in 2 1 5 3 4. The stack holds the indexes still waiting; each new number first settles everything smaller than it
main.cpp
1#include <iostream>2using namespace std;3 4int main() {5    int a[] = {2, 1, 5, 3, 4}, n = 5;6    int ans[5], st[5], t = -1;7    for (int i = 0; i < n; i++) {8        while (t >= 0 && a[i] > a[st[t]])9            ans[st[t--]] = a[i];       // the top's wait is over10        st[++t] = i;11    }12    while (t >= 0)13        ans[st[t--]] = -1;             // never found one14    for (int i = 0; i < n; i++)15        cout << ans[i] << " ";16    cout << "\n";17    return 0;18}
Output
5 5 -1 4 -1 

Each index is pushed once and popped once: O(n). "Next greater / smaller", "daily temperatures" and "largest rectangle in a histogram" all use this pattern.

Choose one

a = 3 1 4 2. What is the "first larger number to the right" of each one, in order (−1 if none)?

Exercise 3

The next smaller number

The opposite of the lesson: for each number find the first number to its right that is smaller, or −1 if none. Use a vector<int> as the monotonic stack.

It should print
3 3 1 1 -1
exercise3.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> a = {4, 6, 3, 5, 1};7    int n = a.size();8    vector<int> ans(n, -1), st;9    for (int i = 0; i < n; i++) {10        // the new number is smaller than the top: it's the top's answer, pop11        st.push_back(i);12    }13    for (int x : ans)14        cout << x << " ";15    cout << "\n";16    return 0;17}
Output
Press Run or Ctrl+Enter

Circular queue questions

Exams define rear in different ways. First check whether rear points at the last element or the next free slot; the formulas change with it:

rear points atLengthFull
the next free slot (as in this course)(rear - front + MAX) % MAX(rear + 1) % MAX == front
the last element itself(rear - front + 1 + MAX) % MAX(rear + 2) % MAX == front

In exams: "a circular queue in an array A[0..n]" means n + 1 slots, so MAX = n + 1, not n.

Choose one

A circular queue with MAX = 10, but this time rear points at the last element itself. front = 7, rear = 2: how many are in it?

With the STL

In interviews none of these three is written with raw arrays. A monotonic stack is most often a vector<int> used as a stack: push_back, back, pop_back, O(1) just like stack<int>, and you can still see every index on it. Below is "daily temperatures": how many days until it's warmer. The answer is a difference of indexes, which is why the stack holds indexes, not values.

main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> temp = {73, 74, 75, 71, 69, 72, 76, 73};7    int n = temp.size();8    vector<int> wait(n, 0);            // 0 if it never gets warmer9    vector<int> st;                    // used as a stack: holds indexes10    for (int i = 0; i < n; i++) {11        while (!st.empty() && temp[i] > temp[st.back()]) {12            wait[st.back()] = i - st.back();13            st.pop_back();14        }15        st.push_back(i);16    }17    for (int w : wait)18        cout << w << " ";19    cout << "\n";20    return 0;21}
Output
1 1 4 2 1 1 0 0 

The queue from two stacks becomes two stack<int>s; this time, count how many elements get poured in all:

main.cpp
1#include <iostream>2#include <stack>3using namespace std;4 5class MyQueue {6    stack<int> in, out;7public:8    int moves = 0;                     // elements poured in all9    void push(int x) { in.push(x); }10    int pop() {11        if (out.empty())12            while (!in.empty()) {13                out.push(in.top());14                in.pop();15                moves++;16            }17        int x = out.top();18        out.pop();19        return x;20    }21};22 23int main() {24    MyQueue q;25    int pops = 0, last = 0;26    for (int i = 1; i <= 1000; i++) {27        q.push(i);28        if (i % 3 == 0) {29            last = q.pop();30            pops++;31        }32    }33    cout << pops << " dequeues, the last one out was " << last << ", " << q.moves << " poured in all\n";34    return 0;35}
Output
333 dequeues, the last one out was 333, 363 poured in all

333 dequeues poured only 363 elements in all, a little over one each: that's amortised O(1). Each element is poured at most once, so the total poured can never exceed the total enqueued.

PatternUsesPer elementIn total
Pop orderstack<int> or an arrayIn once, out onceO(n)
Queue from two stacksTwo stack<int>sPoured at most onceAmortised O(1) each
Monotonic stackvector<int> of indexesIn once, out onceO(n)

In interviews: "The first greater / smaller to the right (or left)" means a monotonic stack holding indexes; "implement a queue with stacks" tests pouring only when out is empty, and the amortised argument; the reverse, "implement a stack with queues", rotates the earlier elements to the back after every push, making push O(n). When real code needs first in first out, just use queue<int> or deque<int>.

Choose one

The MyQueue built from two stack<int>: push 1, 2, 3, pop, push 4, 5, pop, pop, pop. What is moves (how many items were poured over) at the end?

Summary

Take-away

Three stack and queue patterns

  • Pop order: act it out, pop while the top is due, valid only if the stack ends empty
  • Queue from two stacks: pour in over only when out is empty, amortised O(1)
  • Monotonic stack: it holds the indexes waiting for an answer; each new number first settles the smaller ones
  • STL: stack / queue are layers over a deque; a monotonic stack is usually a vector
1while (!st.empty() && a[i] > a[st.back()]) {2    ans[st.back()] = a[i];3    st.pop_back();4}5st.push_back(i);

Chapter 2 quick check

5 questions on circular queues, postfix, matching brackets, a queue from two stacks and pop orders. Work out what each prints before you pick an option.

Guess the outputA wrong guess is fine

A circular queue with MAX = 5 (rear points at the next free slot) has front = 3 and rear = 1. How many are in it?

1#include <iostream>2using namespace std;3 4const int MAX = 5;5 6int main() {7    int front = 3, rear = 1;8    cout << (rear - front + MAX) % MAX << "\n";9    return 0;10}
Guess the outputA wrong guess is fine

Evaluating the postfix expression 2 3 * 5 4 * + 9 −, what does it print?

1#include <iostream>2#include <stack>3#include <string>4using namespace std;5 6int main() {7    string s = "23*54*+9-";8    stack<int> st;9    for (char c : s) {10        if (c >= '0' && c <= '9') {11            st.push(c - '0');12        } else {13            int b = st.top(); st.pop();14            int a = st.top(); st.pop();15            st.push(c == '+' ? a + b : c == '-' ? a - b : a * b);16        }17    }18    cout << st.top() << "\n";19    return 0;20}
Guess the outputA wrong guess is fine

While checking {[()()]}, what's the most brackets on the stack at once?

1#include <iostream>2#include <string>3#include <algorithm>4using namespace std;5 6int main() {7    string s = "{[()()]}";8    int height = 0, best = 0;9    for (char c : s) {10        if (c == '(' || c == '[' || c == '{') height++;11        else height--;12        best = max(best, height);13    }14    cout << best << "\n";15    return 0;16}
Guess the outputA wrong guess is fine

A queue from two stacks: enqueue 1 2, dequeue, enqueue 3 4, dequeue twice more. What does it print?

1#include <iostream>2#include <stack>3using namespace std;4 5stack<int> in, out;6 7void enqueue(int x) { in.push(x); }8 9int dequeue() {10    if (out.empty())11        while (!in.empty()) {12            out.push(in.top());13            in.pop();14        }15    int x = out.top();16    out.pop();17    return x;18}19 20int main() {21    enqueue(1);22    enqueue(2);23    cout << dequeue() << " ";24    enqueue(3);25    enqueue(4);26    cout << dequeue() << " ";27    cout << dequeue() << "\n";28    return 0;29}
Guess the outputA wrong guess is fine

With push order 1 2 3 4, how many pop orders are possible? (next_permutation tries all 24 orderings)

1#include <iostream>2#include <algorithm>3using namespace std;4 5bool valid(const int* out, int n) {6    int st[10], t = -1, k = 0;7    for (int x = 1; x <= n; x++) {8        st[++t] = x;9        while (t >= 0 && st[t] == out[k]) {10            t--;11            k++;12        }13    }14    return t == -1;15}16 17int main() {18    int p[] = {1, 2, 3, 4}, count = 0;19    do {20        if (valid(p, 4)) count++;21    } while (next_permutation(p, p + 4));22    cout << count << "\n";23    return 0;24}