Patterns: stacks and queues
This stack and queue review covers checking whether a pop order is possible, building a queue from two stacks, the monotonic stack for finding the next greater number, and the circular queue calculations exams love.
Stacks and queues themselves are simple; the hard part is seeing which one a problem needs. The four kinds in this lesson keep coming up in exams and interviews; learn one pattern for each.
Is a pop order possible
In the stacks lesson we worked it out by hand: pushed 1 2 3, they can't come out as 3 1 2. As a program, it's just doing it: push in order, and after each push, pop for as long as the top is the next one wanted. If the stack ends up empty, the order can be done.
stack
1231#include <stdio.h>2 3// pushed in the order 1, 2, …, n; out is the pop order wanted4int valid(const int *out, int n) {5 int st[100], top = -1, k = 0;6 for (int x = 1; x <= n; x++) {7 st[++top] = x;8 while (top >= 0 && st[top] == out[k]) {9 top--;10 k++;11 }12 }13 return top == -1;14}15 16int main(void) {17 int a[] = {3, 2, 1}, b[] = {3, 1, 2}, c[] = {2, 4, 3, 1}, d[] = {4, 1, 2, 3};18 printf("3 2 1 %s\n", valid(a, 3) ? "yes" : "no");19 printf("3 1 2 %s\n", valid(b, 3) ? "yes" : "no");20 printf("2 4 3 1 %s\n", valid(c, 4) ? "yes" : "no");21 printf("4 1 2 3 %s\n", valid(d, 4) ? "yes" : "no");22 return 0;23}
3 2 1 yes 3 1 2 no 2 4 3 1 yes 4 1 2 3 no
Each number goes in once and out at most once: O(n).
Pushed in the order 1 2 3 4 5, which of these cannot be the pop order?
Check a pop order
✓Finish valid: pushed in the order 1 to n, can out be the pop order?
1 0 1
1#include <stdio.h>2 3int valid(const int *out, int n) {4 int st[100], top = -1, k = 0;5 for (int x = 1; x <= n; x++) {6 // push x; while the top equals out[k], pop and k++7 }8 return top == -1;9}10 11int main(void) {12 int a[] = {1, 3, 2}, b[] = {3, 1, 2}, c[] = {4, 3, 5, 2, 1};13 printf("%d %d %d\n", valid(a, 3), valid(b, 3), valid(c, 5));14 return 0;15}
A queue from two stacks
An interview favourite: with only stacks, how do you get first in, first out? Use two: in takes everything coming in, out hands everything going out. When out is empty at a dequeue, pour all of in into out: the order flips, and the earliest one in ends up on top of out.
in
123out
3211#include <stdio.h>2 3int in[100], out[100], tin = -1, tout = -1;4 5void enqueue(int x) {6 in[++tin] = x;7}8 9int dequeue(void) {10 if (tout == -1) // pour only when out is empty11 while (tin >= 0)12 out[++tout] = in[tin--];13 return out[tout--];14}15 16int main(void) {17 enqueue(1);18 enqueue(2);19 enqueue(3);20 printf("%d ", dequeue());21 enqueue(4);22 printf("%d ", dequeue());23 printf("%d ", dequeue());24 printf("%d\n", dequeue());25 return 0;26}
1 2 3 4
The key is pouring only when out is empty: pour while out still holds something and the new ones land on top of the old, scrambling the order. Each element is poured exactly once in its life, so although one dequeue may pour a lot, it averages O(1) each (amortized, the same idea as a dynamic array doubling).
in holds 1 2 3 from bottom to top, and out is empty. After one dequeue, what does out hold from bottom to top?
A queue from two stacks
✓Finish dequeue: only when out is empty, pour all of in into it, then take from out.
5 6 7
1#include <stdio.h>2 3int in[100], out[100], tin = -1, tout = -1;4 5void enqueue(int x) {6 in[++tin] = x;7}8 9int dequeue(void) {10 // out empty: pop everything from in and push it onto out11 return out[tout--];12}13 14int main(void) {15 enqueue(5);16 enqueue(6);17 printf("%d ", dequeue());18 enqueue(7);19 printf("%d ", dequeue());20 printf("%d\n", dequeue());21 return 0;22}
The monotonic stack: the next greater number
The problem: for each number, find the first number to its right that is bigger, or −1 if there is none. Two nested loops make it O(n²). The pattern is a monotonic stack: the stack holds the indexes of numbers still waiting for an answer, decreasing from bottom to top. A new number bigger than the top is the top's answer, so pop; keep going until the top isn't smaller, then push it.
i1#include <stdio.h>2 3int main(void) {4 int a[] = {2, 1, 5, 3, 4}, n = 5;5 int ans[5], st[5], top = -1;6 for (int i = 0; i < n; i++) {7 while (top >= 0 && a[i] > a[st[top]])8 ans[st[top--]] = a[i]; // the top's wait is over9 st[++top] = i;10 }11 while (top >= 0)12 ans[st[top--]] = -1; // never found one13 for (int i = 0; i < n; i++)14 printf("%d ", ans[i]);15 printf("\n");16 return 0;17}
5 5 -1 4 -1
Each index is pushed once and popped once: O(n). "Next greater / smaller", "largest rectangle in a histogram" and "daily temperatures" all use this pattern.
a = 3 1 4 2. What is the "first larger number to the right" of each one, in order (−1 if none)?
The next smaller number
✓The other way round from the lesson: for each number find the first number to its right that is smaller, or −1. Use a monotonic stack.
3 3 1 1 -1
1#include <stdio.h>2 3int main(void) {4 int a[] = {4, 6, 3, 5, 1}, n = 5;5 int ans[5], st[5], top = -1;6 for (int i = 0; i < n; i++) {7 // a new number smaller than the top is the top's answer8 st[++top] = i;9 }10 while (top >= 0)11 ans[st[top--]] = -1;12 for (int i = 0; i < n; i++)13 printf("%d ", ans[i]);14 printf("\n");15 return 0;16}
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 at | Length | Full |
|---|---|---|
| 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.
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?
Summary
Four stack and queue patterns
- Pop orders: push in order, pop whenever the top is due; possible only if it ends empty
- Queue from two stacks: pour in into out only when out is empty, amortized O(1)
- Monotonic stack: it holds the indexes waiting; each new number settles the smaller ones first
- Circular queue: first check whether rear is the last element or the next free slot
1while (top >= 0 && a[i] > a[st[top]])2 ans[st[top--]] = a[i];3st[++top] = i;
Chapter 2 quick check
5 questions on circular queues, postfix expressions, matching brackets, a queue made of two stacks and pop orders. Work out what each prints before you pick.
A circular queue with MAX = 5 (rear points at the next free slot), front = 3, rear = 1. How many are in it?
1#include <stdio.h>2 3#define MAX 54 5int main(void) {6 int front = 3, rear = 1;7 printf("%d\n", (rear - front + MAX) % MAX);8 return 0;9}
Evaluate the postfix expression 2 3 * 5 4 * + 9 −. What does it print?
1#include <stdio.h>2#include <ctype.h>3 4int main(void) {5 const char *s = "23*54*+9-";6 int st[20], top = -1;7 for (int i = 0; s[i] != '\0'; i++) {8 char c = s[i];9 if (isdigit(c)) {10 st[++top] = c - '0';11 } else {12 int b = st[top--], a = st[top--];13 st[++top] = c == '+' ? a + b : c == '-' ? a - b : a * b;14 }15 }16 printf("%d\n", st[top]);17 return 0;18}
Checking {[()()]}, what is the most brackets on the stack at once?
1#include <stdio.h>2 3int main(void) {4 const char *s = "{[()()]}";5 int top = -1, best = 0;6 for (int i = 0; s[i] != '\0'; i++) {7 if (s[i] == '(' || s[i] == '[' || s[i] == '{') top++;8 else top--;9 if (top + 1 > best) best = top + 1;10 }11 printf("%d\n", best);12 return 0;13}
A queue made of two stacks: enqueue 1 2, dequeue, enqueue 3 4, dequeue twice. What does it print?
1#include <stdio.h>2 3int in[10], out[10], tin = -1, tout = -1;4 5void enqueue(int x) { in[++tin] = x; }6 7int dequeue(void) {8 if (tout == -1)9 while (tin >= 0)10 out[++tout] = in[tin--];11 return out[tout--];12}13 14int main(void) {15 enqueue(1);16 enqueue(2);17 printf("%d ", dequeue());18 enqueue(3);19 enqueue(4);20 printf("%d ", dequeue());21 printf("%d\n", dequeue());22 return 0;23}
Pushing 1 2 3 4 in order, how many pop orders are possible? (The program tries all 24 orderings.)
1#include <stdio.h>2 3int valid(const int *out, int n) {4 int st[10], top = -1, k = 0;5 for (int x = 1; x <= n; x++) {6 st[++top] = x;7 while (top >= 0 && st[top] == out[k]) {8 top--;9 k++;10 }11 }12 return top == -1;13}14 15int main(void) {16 int p[4], count = 0;17 for (p[0] = 1; p[0] <= 4; p[0]++)18 for (p[1] = 1; p[1] <= 4; p[1]++)19 for (p[2] = 1; p[2] <= 4; p[2]++)20 for (p[3] = 1; p[3] <= 4; p[3]++) {21 int seen = 0;22 for (int i = 0; i < 4; i++) seen |= 1 << p[i];23 if (seen == 30 && valid(p, 4)) count++;24 }25 printf("%d\n", count);26 return 0;27}