A simple array queue has a problem: after a few dequeues, the free slots are all at the front, and the queue says “full” even though space is available. A circular queue fixes this by treating the array as a ring, so indexes wrap from the last slot back to the first with the % operator. Extending the same idea to both ends gives a deque (double-ended queue), which can add and remove at the front and the back in O(1).
In this lesson you will learn
- Why a linear array queue wastes space
- Implementing a circular queue with
frontandcount - Wrapping indexes with the modulo operator
- Building a deque on a circular array
- Using a deque for the sliding window maximum problem
This lesson extends the Queue Data Structure.
Circular Queue
#include <stdio.h>
#include <stdbool.h>
#define CAP 5
/* Circular queue: the array is reused by wrapping indexes with % */
struct Queue {
int items[CAP];
int front; /* index of the first element */
int count; /* number of elements stored */
};
bool enqueue(struct Queue *q, int v) {
if (q->count == CAP) return false; /* full */
int rear = (q->front + q->count) % CAP;
q->items[rear] = v;
q->count++;
return true;
}
bool dequeue(struct Queue *q, int *out) {
if (q->count == 0) return false; /* empty */
*out = q->items[q->front];
q->front = (q->front + 1) % CAP;
q->count--;
return true;
}
void show(const struct Queue *q) {
printf("front=%d count=%d queue: ", q->front, q->count);
for (int i = 0; i < q->count; i++) printf("%d ", q->items[(q->front + i) % CAP]);
printf("\n");
}
int main(void) {
struct Queue q = { {0}, 0, 0 };
int x;
for (int v = 1; v <= 5; v++) enqueue(&q, v * 10);
show(&q);
printf("enqueue 60 when full: %s\n", enqueue(&q, 60) ? "ok" : "rejected");
dequeue(&q, &x); printf("dequeued %d\n", x);
dequeue(&q, &x); printf("dequeued %d\n", x);
enqueue(&q, 60); /* goes into slot 0: wrap-around */
enqueue(&q, 70);
show(&q);
return 0;
}
Output
front=0 count=5 queue: 10 20 30 40 50
enqueue 60 when full: rejected
dequeued 10
dequeued 20
front=2 count=5 queue: 30 40 50 60 70
- The queue stores the index of the first element (
front) and how many elements there are (count). The back position is calculated as(front + count) % CAP. - Keeping
countavoids the classic puzzle of telling “full” from “empty” whenfrontequalsrear. - When the queue holds 5 items,
enqueuereturnsfalseinstead of overwriting data. - After two dequeues,
frontis 2. The next two enqueues go to slots 0 and 1 because the index wraps around. The array is reused completely, and the printed order is still first-in, first-out.
Deque and the Sliding Window Maximum
#include <stdio.h>
#include <stdbool.h>
#define CAP 8
/* Deque: insert and remove at both ends, built on a circular array */
struct Deque { int a[CAP]; int front, count; };
bool push_front(struct Deque *d, int v) {
if (d->count == CAP) return false;
d->front = (d->front - 1 + CAP) % CAP; /* step back, wrapping */
d->a[d->front] = v;
d->count++;
return true;
}
bool push_back(struct Deque *d, int v) {
if (d->count == CAP) return false;
d->a[(d->front + d->count) % CAP] = v;
d->count++;
return true;
}
int pop_front(struct Deque *d) {
int v = d->a[d->front];
d->front = (d->front + 1) % CAP;
d->count--;
return v;
}
int pop_back(struct Deque *d) {
d->count--;
return d->a[(d->front + d->count) % CAP];
}
int peek_front(const struct Deque *d) { return d->a[d->front]; }
int peek_back(const struct Deque *d) { return d->a[(d->front + d->count - 1) % CAP]; }
/* Sliding window maximum with a deque of indexes */
void window_max(const int *arr, int n, int k) {
struct Deque d = { {0}, 0, 0 };
printf("Window maxima (k=%d): ", k);
for (int i = 0; i < n; i++) {
if (d.count && peek_front(&d) <= i - k) pop_front(&d); /* left the window */
while (d.count && arr[peek_back(&d)] <= arr[i]) pop_back(&d); /* smaller, useless */
push_back(&d, i);
if (i >= k - 1) printf("%d ", arr[peek_front(&d)]);
}
printf("\n");
}
int main(void) {
struct Deque d = { {0}, 0, 0 };
push_back(&d, 2); push_back(&d, 3); push_front(&d, 1); push_front(&d, 0);
printf("front=%d back=%d count=%d\n", peek_front(&d), peek_back(&d), d.count);
int a = pop_front(&d);
int b = pop_back(&d);
printf("pop_front -> %d, pop_back -> %d, count=%d\n", a, b, d.count);
int arr[] = {4, 2, 12, 3, 8, 7, 1, 9};
window_max(arr, 8, 3);
return 0;
}
Output
front=0 back=3 count=4
pop_front -> 0, pop_back -> 3, count=2
Window maxima (k=3): 12 12 12 8 8 9
push_frontmovesfrontone step back. AddingCAPbefore taking% CAPkeeps the index from becoming negative, because-1 % 8is -1 in C.pop_backjust shrinkscount; the last element’s position is(front + count) % CAP.- The two pops are done in separate statements. Writing both calls as arguments of one
printfwould leave their order up to the compiler. window_maxkeeps indexes in the deque, with their values in decreasing order. Indexes that slide out of the window are removed from the front; smaller values are removed from the back because they can never be a maximum again. The front is always the current maximum.- Each index is pushed and popped at most once, so the whole scan is O(n) instead of O(n·k). Compare this with the sliding window technique for sums.
Queue Variants
| Structure | Add | Remove | Typical use |
|---|---|---|---|
| Queue (FIFO) | Back | Front | Print jobs, BFS |
| Circular queue | Back | Front | Keyboard and network buffers, streaming audio |
| Deque | Front or back | Front or back | Sliding windows, undo history, work stealing |
| Priority queue | Anywhere | Highest priority | Scheduling, Dijkstra |
Common Mistakes
- Negative indexes when stepping backwards: use
(i - 1 + CAP) % CAP. - Not checking full or empty before adding or removing.
- Confusing full and empty when only
frontandrearare stored; keep a count or leave one slot unused. - Storing values instead of indexes in the sliding window deque, which makes it impossible to know when an element has left the window.
Practice Exercises
Exercise 1. Add a peek function to the circular queue that returns the front value without removing it.
Show answer
bool peek(const struct Queue *q, int *out) {
if (q->count == 0) return false;
*out = q->items[q->front];
return true;
}
Exercise 2. Use a deque to check whether a word is a palindrome by comparing letters taken from both ends.
Show answer
bool is_palindrome(const char *s) {
struct Deque d = { {0}, 0, 0 };
for (; *s; s++) push_back(&d, *s);
while (d.count > 1) {
int first = pop_front(&d);
int last = pop_back(&d);
if (first != last) return false;
}
return true;
}
Frequently Asked Questions
What is a ring buffer?
It is another name for a circular queue. Ring buffers are used wherever data arrives continuously and only the most recent part matters, such as audio streaming and logging.
Can a deque replace both a stack and a queue?
Yes. Using only one end makes it a stack; adding at one end and removing at the other makes it a queue.
Summary
- A circular queue reuses array slots by wrapping indexes with
%. - Store
frontandcountto tell full from empty easily. - A deque supports O(1) operations at both ends.
- The monotonic deque solves the sliding window maximum in O(n).
Next: AVL Tree in C.
