5.7Exam Practice
Queue: exam questions and answers
This page is the exam practice for the queue section. University exams ask about queues in a few recurring ways: comparing linear and circular queues, tracing front and rear after a series of operations, telling a full queue from an empty one, coding enqueue and dequeue, building a queue from two stacks, and tracing a priority queue. Here you get original questions of each kind with step-by-step answers.
- How to trace
front,rearandcountin linear and circular arrays with a table - How to code enqueue and dequeue with an array, a linked list and a circular linked list
- How to compare priority queues, the two-stack queue and the cost of each operation
1Conceptual questions
The questions are original, but their types were picked from the kinds that often appear in published midterm and final exams of universities in Turkey and abroad. Solve each question yourself first, then open the box and compare your answer. Write a queue with the front on the left and the rear on the right: in the queue [4, 7, 1], 4 is at the front. The function names in the code match those in the lessons on the array queue, the circular queue and the linked-list queue.
1What principle does a queue follow? At which ends are elements added and removed? Name three places where computers use a queue.Midterm · concept
A queue follows the FIFO principle: first in, first out. Enqueue adds an element at the rear (rear), and dequeue removes one from the front (front). The two operations work at two different ends.
- Print queues: documents are printed in the order they were sent.
- Process scheduling in an operating system: round-robin runs processes in turn from a queue.
- Network and keyboard buffers: incoming packets and keys are handled in the order they arrive.
Breadth-first search in a graph also uses a queue: near nodes are visited first, then the ones farther away. See What is a queue?.
2What is the difference between a linear array queue and a circular queue? What is the advantage of the circular queue?Midterm · concept
In a linear queue front and rear only move forward. Dequeue frees cells at the front, but they are never used again. When rear reaches the end of the array, the queue counts as full even if the front cells are empty. In a circular queue the index goes back to the start with mod when it reaches the end, so freed cells are used again.
| Linear queue | Circular queue | |
|---|---|---|
| Moving an index | rear++, front++ | (rear + 1) % CAPACITY |
| Empty cells at the front | Wasted | Used again |
| Counts as full when | rear == CAPACITY - 1 | count == CAPACITY |
| Shifting | None (or O(n) on every dequeue) | None |
One way to fix the linear queue is to shift the elements left on every dequeue, but that makes dequeue O(n). A circular queue wastes no space and keeps every operation O(1). See Wasted cells.
3If a circular queue keeps only front and rear (no count), why can a full queue not be told apart from an empty one? How is this solved?Midterm · concept
Let rear point at the last element. In an empty queue front is the cell after rear: (rear + 1) % n == front. Fill the queue with n elements and rear comes around to the cell just before front again; the condition is the same. The two indexes have the same values, yet one queue is empty and the other is full.
- Keep the element count:
count == 0means empty,count == nmeans full. The code on this site does this. - Always leave one cell empty: at most n - 1 elements are stored. In this method
rearusually points at the first free cell;front == rearmeans empty and(rear + 1) % n == frontmeans full. - Keep a flag for whether the last operation was an enqueue or a dequeue: when the indexes meet, the queue is full if it was an enqueue and empty if it was a dequeue.
All three keep the operations O(1). Leaving a cell empty costs one element of space; count updates one more number on each operation. See Full or empty?.
4Compare a stack and a queue. What is a deque (double-ended queue), and how can a stack and a queue be defined in terms of it?Final · concept
A stack works LIFO and a queue works FIFO. In a stack adding and removing happen at the same end; in a queue adding is at the rear and removing at the front. A deque allows all four operations: push at the front or back, pop from the front or back.
| Structure | Add | Remove | As a deque |
|---|---|---|---|
| Stack | Top | Top | pushBack + popBack |
| Queue | Rear | Front | pushBack + popFront |
| Deque | Both ends | Both ends | All four operations |
So a stack and a queue are each a deque with restricted operations. That is why Java's java.util.ArrayDeque class is used both as a stack and as a queue. See Deque: double-ended queue.
2Tracing questions
5A linear array queue with capacity 5 is empty (front = 0, rear = -1). You run enqueue 10, enqueue 20, enqueue 30, dequeue, dequeue, enqueue 40, enqueue 50, enqueue 60. Write front and rear after each operation. Which operation fails, and how many elements are in the queue at that moment?Midterm · trace
enqueue 60 fails because rear has reached 4, which is CAPACITY - 1. At that moment the queue holds only 3 elements (30, 40, 50); cells 0 and 1 are empty, but a linear queue cannot use them.
| Operation | Returns | front | rear | Queue (front → rear) |
|---|---|---|---|---|
| enqueue 10 | 0 | 0 | 10 | |
| enqueue 20 | 0 | 1 | 10, 20 | |
| enqueue 30 | 0 | 2 | 10, 20, 30 | |
| dequeue | 10 | 1 | 2 | 20, 30 |
| dequeue | 20 | 2 | 2 | 30 |
| enqueue 40 | 2 | 3 | 30, 40 | |
| enqueue 50 | 2 | 4 | 30, 40, 50 | |
| enqueue 60 | full | 2 | 4 | 30, 40, 50 |
In a linear queue the element count is rear - front + 1: 4 - 2 + 1 = 3. This question shows why a circular queue is needed. See Wasted cells.
6A circular queue with capacity 5 is empty (front = 0, rear = -1, count = 0). You run enqueue 1, 2, 3, 4; dequeue, dequeue; enqueue 5, 6, 7, 8; dequeue. Write front, rear and count at each step. What is in the items array at the end, and what is the order of the queue?Midterm · trace
enqueue 8 fails because count is 5 at that moment. At the end front = 3, rear = 1 and count = 4. The items array holds 6, 7, 3, 4, 5 from left to right, but the queue is read starting at front: 4, 5, 6, 7. The 3 in cell 2 is no longer part of the queue.
| Operation | Returns | front | rear | count |
|---|---|---|---|---|
| enqueue 1, 2, 3, 4 | 0 | 3 | 4 | |
| dequeue | 1 | 1 | 3 | 3 |
| dequeue | 2 | 2 | 3 | 2 |
| enqueue 5 | 2 | 4 | 3 | |
| enqueue 6 | 2 | 0 (wrapped) | 4 | |
| enqueue 7 | 2 | 1 | 5 | |
| enqueue 8 | full | 2 | 1 | 5 |
| dequeue | 3 | 3 | 1 | 4 |
rear went from 4 to 0 with (4 + 1) % 5 = 0. That is why it is hard to say full or empty by looking at front and rear; count settles it with one comparison.
7Some textbooks let rear in a circular queue point at the cell after the last element, the first free cell, and always leave one cell empty. How do you compute the element count then? For n = 8, how many elements are there when (a) front = 2, rear = 6; (b) front = 6, rear = 2; (c) front = rear = 5? How many elements can the queue hold at most?Midterm · trace
The element count is (rear - front + n) % n. The + n keeps the difference from going negative when rear has wrapped around to the left of front.
| Case | Calculation | Elements | Used cells |
|---|---|---|---|
| (a) front 2, rear 6 | (6 - 2 + 8) % 8 | 4 | 2, 3, 4, 5 |
| (b) front 6, rear 2 | (2 - 6 + 8) % 8 | 4 | 6, 7, 0, 1 |
| (c) front 5, rear 5 | (5 - 5 + 8) % 8 | 0 | none, the queue is empty |
Since one cell always stays empty, the queue holds at most n - 1 = 7 elements. It is full when (rear + 1) % n == front. In this site's code rear points at the last element; there the formula is (rear - front + 1 + n) % n, but it gives 0 for a full queue too, so count is kept as well.
8A queue built from two stacks (inbox and outbox) runs enqueue 1, enqueue 2, dequeue, enqueue 3, enqueue 4, dequeue, dequeue, enqueue 5, dequeue. What does each dequeue return, what is left in the two stacks, and how many pushes and pops happen in total?Final · trace
The dequeues return 1, 2, 3 and 4 in that order. At the end inbox holds 5 and outbox is empty. 17 stack operations happen in total. Elements are moved only when outbox is empty, and each moved element costs one pop and one push.
| Operation | Returns | inbox (top on the right) | outbox (top on the right) | Stack operations |
|---|---|---|---|---|
| enqueue 1, enqueue 2 | 1 2 | empty | 2 | |
| dequeue | 1 | empty | 2 | move 4 + pop 1 = 5 |
| enqueue 3, enqueue 4 | 3 4 | 2 | 2 | |
| dequeue | 2 | 3 4 | empty | 1 |
| dequeue | 3 | empty | 4 | move 4 + pop 1 = 5 |
| enqueue 5 | 5 | 4 | 1 | |
| dequeue | 4 | 5 | empty | 1 |
Each element goes through at most four stack operations: push onto inbox, pop from inbox, push onto outbox, pop from outbox. For 5 elements the limit is 20; we stopped at 17 because 5 has not left yet. That is why each operation costs amortized O(1). See Queue with two stacks.
9A linked-list queue is empty. You run enqueue 7, enqueue 4, dequeue, dequeue, enqueue 9. Write the node front and rear point at after each step. What happens if dequeue does not set rear to NULL when it removes the last node?Midterm · trace
At the end the queue has one node: front and rear both point at 9. The real trap is the fourth step: when 4 leaves, the list is empty, and rear must become NULL along with front.
| Operation | Returns | front | rear |
|---|---|---|---|
| enqueue 7 | 7 | 7 | |
| enqueue 4 | 7 | 4 | |
| dequeue | 7 | 4 | 4 |
| dequeue | 4 | NULL | NULL |
| enqueue 9 | 9 | 9 |
If rear is not set to NULL, it points at the freed node 4. The next enqueue does not see an empty queue, writes into freed memory with rear->next = node, and front stays NULL. The new element never shows up in the queue. See Linked-list dequeue.
3Code reading questions
Code for the next question (Python, circular queue with front, rear and count fields):
q = CircularQueue(5)for x in (3, 8, 5, 2): q.enqueue(x)for _ in range(3): x = q.dequeue() if x % 2 == 1: q.enqueue(x * 2)print(q.peek(), q.count, q.front, q.rear)while not q.is_empty(): print(q.dequeue(), end=" ")10What does the code above print? Why do front and rear have these values on the first print line?Midterm · code reading
The first line is 2 3 3 0 and the second is 2 6 10. The loop doubles odd numbers and puts them back at the rear, and drops even numbers. rear looks smaller than front because it wrapped from 4 to 0.
| Step | Queue (front → rear) | front | rear | count |
|---|---|---|---|---|
| Four enqueues | 3, 8, 5, 2 | 0 | 3 | 4 |
| x = 3, odd: enqueue 6 | 8, 5, 2, 6 | 1 | 4 | 4 |
| x = 8, even | 5, 2, 6 | 2 | 4 | 3 |
| x = 5, odd: enqueue 10 | 2, 6, 10 | 3 | 0 | 3 |
peek gives the 2 at the front without removing it. The last loop empties the queue and prints 2, 6, 10.
Code for the next question (C, circular queue):
bool enqueue(struct Queue* q, int value) { if (q->count == CAPACITY) return false; q->rear = q->rear + 1 % CAPACITY; q->items[q->rear] = value; q->count++; return true;}11This enqueue function has a bug. What is it, and when does it show up? Fix it.Midterm · code reading
The bug is operator precedence. % is applied before +, so the line runs as q->rear + (1 % CAPACITY), which is q->rear + 1. rear never wraps.
It shows up when elements have left the front before the queue fills. For example, with capacity 5, after 5 enqueues and 1 dequeue count is 4 and rear is 4. The next enqueue sets rear to 5 and writes to items[5], outside the array. The fix is parentheses:
q->rear = (q->rear + 1) % CAPACITY;Code for the next question (Python, the library queue collections.deque):
from collections import deque def mystery(n, k): q = deque(range(1, n + 1)) removed = [] while len(q) > 1: for _ in range(k - 1): q.append(q.popleft()) removed.append(q.popleft()) return removed, q[0]12What does mystery(7, 3) return? What does the function do?Final · code reading
It returns ([3, 6, 2, 7, 5, 1], 4). The numbers 1 to n sit in the queue like a circle. In each round k - 1 people are taken from the front and put at the rear, and the k-th person is removed. The last one left is returned. This is known as the Josephus problem.
| Round | Queue after rotating | Removed | Queue left |
|---|---|---|---|
| 1 | 3, 4, 5, 6, 7, 1, 2 | 3 | 4, 5, 6, 7, 1, 2 |
| 2 | 6, 7, 1, 2, 4, 5 | 6 | 7, 1, 2, 4, 5 |
| 3 | 2, 4, 5, 7, 1 | 2 | 4, 5, 7, 1 |
| 4 | 7, 1, 4, 5 | 7 | 1, 4, 5 |
| 5 | 5, 1, 4 | 5 | 1, 4 |
| 6 | 1, 4 | 1 | 4 |
Each removal takes k - 1 rotations and one dequeue; n - 1 people leave, so the time is O(n · k).
4Code writing questions
13Write enqueue and dequeue in C for a circular array queue. The struct is struct Queue { int items[CAPACITY]; int front; int rear; int count; }, and an empty queue has front = 0, rear = -1, count = 0.Midterm · code writing
Enqueue first checks for a full queue, moves rear forward with mod, writes, and increases count. Dequeue first checks for an empty queue, reads the value at front, moves front forward with mod, and decreases count.
bool enqueue(struct Queue* q, int value) { if (q->count == CAPACITY) return false; // queue is full q->rear = (q->rear + 1) % CAPACITY; // wrap to the start at the end q->items[q->rear] = value; q->count++; return true;} bool dequeue(struct Queue* q, int* value) { if (q->count == 0) return false; // queue is empty *value = q->items[q->front]; q->front = (q->front + 1) % CAPACITY; q->count--; return true;}A common mistake is mixing up the order in dequeue: if front moves first, the element after the front one is read. Both operations take O(1). See Circular queue enqueue and dequeue.
14Write enqueue and dequeue in C for a linked-list queue. The struct is struct Queue { struct Node* front; struct Node* rear; }.Midterm · code writing
Enqueue links the new node after rear; if the queue is empty, front points at the new node too. Dequeue removes front; if the list becomes empty, rear is set to NULL as well.
bool enqueue(struct Queue* q, int value) { struct Node* node = malloc(sizeof(struct Node)); if (node == NULL) return false; // out of memory node->data = value; node->next = NULL; if (q->rear == NULL) // empty queue q->front = node; else q->rear->next = node; // link after the last node q->rear = node; return true;} bool dequeue(struct Queue* q, int* value) { if (q->front == NULL) return false; // queue is empty struct Node* temp = q->front; *value = temp->data; q->front = temp->next; if (q->front == NULL) // the last node left q->rear = NULL; free(temp); return true;}Since the two ends are held in separate pointers, both operations take O(1). Without rear, enqueue would walk to the end every time and take O(n). There is no capacity; enqueue returns false only if malloc fails.
15Write a queue on a circular linked list with a single pointer: the struct holds only rear. How are enqueue and dequeue written in C?Final · code writing
In a circular list the last node points at the first; the front node is rear->next. So one pointer reaches both ends in O(1). Enqueue puts the new node between rear and rear->next and makes it rear. Dequeue removes rear->next.
bool enqueue(struct Queue* q, int value) { struct Node* node = malloc(sizeof(struct Node)); if (node == NULL) return false; node->data = value; if (q->rear == NULL) { node->next = node; // a single node points to itself } else { node->next = q->rear->next; // the new node points to the front q->rear->next = node; } q->rear = node; return true;} bool dequeue(struct Queue* q, int* value) { if (q->rear == NULL) return false; // queue is empty struct Node* head = q->rear->next; // the front node *value = head->data; if (head == q->rear) // there was a single node q->rear = NULL; else q->rear->next = head->next; free(head); return true;}There are two special cases: the first element in an empty queue points at itself, and when the only node leaves, rear becomes NULL. See Queue with one pointer.
16Using only queue operations (enqueue, dequeue, is empty) and one stack, write a function that reverses a queue.Midterm · code writing
Until the queue is empty, elements are taken from the front and pushed onto the stack. Then, until the stack is empty, they are popped and added back to the queue. Since the stack is LIFO, the last one in, the last element of the queue, comes back first.
def reverse(q): s = [] # helper stack while not q.is_empty(): s.append(q.dequeue()) # the front element goes onto the stack while s: q.enqueue(s.pop()) # last in comes back firstIf the queue is [1, 2, 3, 4], the stack (bottom → top) becomes [1, 2, 3, 4], and after moving back the queue is [4, 3, 2, 1]. Each element sees one dequeue, one push, one pop and one enqueue; time and extra memory are O(n).
17Write a queue class using two stacks (Java). Explain the worst-case and amortized cost of dequeue.Final · code writing
Enqueue always pushes onto inbox. Dequeue pops from outbox; if outbox is empty, every element in inbox is moved over first. The move reverses the order, so the oldest element ends up on top of outbox.
class TwoStackQueue { java.util.ArrayDeque<Integer> inbox = new java.util.ArrayDeque<>(); java.util.ArrayDeque<Integer> outbox = new java.util.ArrayDeque<>(); void enqueue(int value) { inbox.push(value); } int dequeue() { if (outbox.isEmpty()) { if (inbox.isEmpty()) throw new IllegalStateException("queue is empty"); while (!inbox.isEmpty()) outbox.push(inbox.pop()); // the order flips } return outbox.pop(); }}A single dequeue takes O(n) if inbox holds n elements. But each element is moved at most once, so n operations take O(n) in total and each costs amortized O(1). Moving while outbox still holds elements breaks the order.
5Priority queue questions
18A priority queue built on a linked list sorted from small to large is empty (a smaller value has higher priority; among equals, the earlier one leaves first). You run insert 5, insert 2, insert 8, insert 2, insert 1, removeMin, removeMin. Write the list after each step.Midterm · priority queue
Insert walks the list until it finds the first node larger than the new value and puts the new node before it. The new node goes behind equal values, so the 2 that came first stays in front. Removal is from the head. To tell the two 2s apart, call the second one 2'.
| Operation | List (head → tail) | Returns | Note |
|---|---|---|---|
| insert 5 | 5 | into the empty list | |
| insert 2 | 2, 5 | at the head | |
| insert 8 | 2, 5, 8 | at the tail | |
| insert 2' | 2, 2', 5, 8 | behind the equal one | |
| insert 1 | 1, 2, 2', 5, 8 | at the head | |
| removeMin | 2, 2', 5, 8 | 1 | from the head |
| removeMin | 2', 5, 8 | 2 | the 2 that came first |
In the worst case insert walks the whole list, O(n). Removal is O(1). See Linked-list insert.
19A priority queue can be built with four structures: an unsorted array, a sorted array, a sorted linked list and a heap. Compare the cost of insert, removing the highest priority element, and looking at it.Final · priority queue
With sorted structures the work falls on insert; with an unsorted one it falls on removal. A heap balances both at O(log n).
| Structure | Insert | Remove | Look (peek) |
|---|---|---|---|
| Unsorted array | O(1), add at the end | O(n), search and close the gap | O(n) |
| Sorted array (large to small) | O(n), shifting | O(1), from the end | O(1) |
| Sorted linked list | O(n), find the place | O(1), from the head | O(1) |
| Heap | O(log n) | O(log n) | O(1) |
With few elements and frequent removals a sorted structure is enough. With many elements and mixed operations a heap is chosen; n operations then take O(n log n) instead of O(n²). See Which structure?.
20Write insert and removeMin in C for a priority queue on an array sorted from large to small. Among equal priorities, the earlier one must leave first.Final · priority queue
The highest priority (smallest) element is at the end of the array; removal only decreases size. Insert walks from the end toward the start, shifts the values smaller than or equal to the new one a cell to the right, then writes into the opened cell.
bool insert(struct PQ* pq, int value) { if (pq->size == CAPACITY) return false; // queue is full int i = pq->size - 1; while (i >= 0 && pq->items[i] <= value) { // higher priority and equal ones move right pq->items[i + 1] = pq->items[i]; i--; } pq->items[i + 1] = value; pq->size++; return true;} bool removeMin(struct PQ* pq, int* value) { if (pq->size == 0) return false; // queue is empty *value = pq->items[--pq->size]; // the highest priority is at the end return true;}Shifting the equal values matters: with < instead of <=, the new element lands to the right of its equals, closer to the end, and leaves before them. Insert is O(n) and removal O(1). See Array insert.
21An emergency room sorts patients into three priority groups: red (0), yellow (1), green (2). Within a group, patients are seen in order of arrival. Write this using one queue per group. If the arrivals are P1 green, P2 yellow, P3 green, P4 red, P5 yellow, in what order are the patients seen?Final · priority queue
The order is P4, P2, P5, P1, P3. Each group is a FIFO queue of its own. Removal starts at the highest priority group and takes the front of the first queue that is not empty.
from collections import deque class GroupedQueue: def __init__(self, levels): self.queues = [deque() for _ in range(levels)] # 0 is the highest priority def insert(self, name, priority): self.queues[priority].append(name) # to the rear of its own group def remove_min(self): for q in self.queues: # start from the highest priority group if q: return q.popleft() raise IndexError("queue is empty")With g groups, insert takes O(1) and removal O(g); since g is fixed, both count as O(1). When there are few fixed priority values, this structure beats both a sorted list and a heap, and it keeps arrival order among equals by itself.
6Complexity and comparison questions
22Compare queues built on a linear array, a circular array, a linked list, a circular linked list with one pointer, and two stacks, in terms of enqueue, dequeue and memory.Midterm · complexity
Except for the two-stack queue, every structure does enqueue and dequeue in O(1); the differences are in memory and limits.
| Structure | enqueue | dequeue | Memory and limit |
|---|---|---|---|
| Linear array | O(1) | O(1) | Cells at the front are wasted |
| Circular array | O(1) | O(1) | Fixed capacity, no wasted space |
| Linked list (front, rear) | O(1) | O(1) | No limit, one pointer per node |
| Circular linked list (rear) | O(1) | O(1) | No limit, one pointer in the struct |
| Two stacks | O(1) | Amortized O(1), worst O(n) | The total of the two stacks |
In a linear array "full" means less than it says: the queue counts as full when rear reaches the end, even with few elements inside. See Array or linked list?.
23If a linked-list queue keeps only front, what do enqueue and dequeue cost? And if the list is built the other way round, with the front at the tail?Final · complexity
With only front, dequeue removes the head, O(1). But enqueue walks the whole list to add at the end, O(n).
| Kept | enqueue | dequeue |
|---|---|---|
| Only front (head) | O(n) | O(1) |
| front (head) + rear (tail) | O(1) | O(1) |
| Front at the tail, rear at the head | O(1), add at the head | O(n), remove from the tail |
Built the other way round, the problem moves: in a singly linked list, removing from the tail means walking from the head to find the node before the last. That is why the front is kept at the head, the rear at the tail, and both pointers are stored.
24You want to write a deque on a singly linked list (keeping head and tail). Which operation will not be O(1)? How do you fix it?Final · comparison
Popping from the back will not be O(1). tail points at the last node, but there is no link from the last node to the one before it; finding that one means walking from the head, O(n).
| Operation | Singly linked list | Doubly linked list | Circular array |
|---|---|---|---|
| Push front | O(1) | O(1) | O(1) |
| Push back | O(1) | O(1) | O(1) |
| Pop front | O(1) | O(1) | O(1) |
| Pop back | O(n) | O(1) | O(1) |
The fix is a doubly linked list: each node also points at the one before it, so tail = tail.prev removes the last node in O(1). Or the deque is written on a circular array. See Deque.
7Try it
A circular queue with capacity 6 has front = 4 and count = 3. At which index is the last element?
The answer is A. The elements are in cells 4, 5 and 0: (4 + 3 - 1) % 6 = 0.
Show the answer
The answer is A. The elements are in cells 4, 5 and 0: (4 + 3 - 1) % 6 = 0.
What must happen when dequeue removes the last node of a linked-list queue?
The answer is B. Once the list is empty, rear must not point at the freed node. Otherwise the next enqueue writes into it.
Show the answer
The answer is B. Once the list is empty, rear must not point at the freed node. Otherwise the next enqueue writes into it.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.